Postgresql joins 2 tables and subquery with last value <date
I have 3 tables: bill_plans, biling_types, users
Sample data
Bill_plans
id, user_id, bill_plan_value, bill_type_id, bill_plan_date
1 1 100 7 2017-04-13
2 1 50 4 2017-03-13
3 1 70 7 2017-03-24
4 1 28 3 2017-02-21
Billing_types
id, bill_type, parent_id
3 1
4 1
5 ΡΡ 2
6 2
7 2
2 ΡΡ ΡΡ 0
1 ΡΡ ΡΡ 0
Users
id, name
1, Ρ
2, Carl
3, Peter
You need to get
id, user_id, bill_plan_value, bill_type_id, bill_plan_date, bill_type, name
1 1 100 7 2017-04-13 Ρ
2 NULL NULL 6 NULL Ρ
3 NULL NULL 5 NULL ΡΡ Ρ
4 NULL NULL 4 NULL Ρ
5 NULL NULL 3 NULL Ρ
And with other users
Tried to work
SELECT b.*, bt.*, u.name
FROM bill_plans as b
FULL JOIN billing_types as bt ON bt.id = b.bill_type_id
FULL JOIN users as u ON u.id = b.user_id
WHERE EXTRACT (MONTH FROM b.bill_plan_date) = $dateMonth OR
b.bill_plan_date IS NULL AND bt.parent_id != 0 OR bt.parent_id IS NULL
how
[0]=>
array(8) {
["id"]=>
int(7)
["user_id"]=>
int(1)
["bill_plan_value"]=>
string(3) "100"
["bill_type_id"]=>
int(7)
["bill_plan_date"]=>
string(10) "2017-04-13"
["bill_type"]=>
string(16) "Tax"
["parent_id"]=>
int(2)
["name"]=>
string(10) "User1"
}
[1]=>
array(8) {
["id"]=>
int(5)
["user_id"]=>
NULL
["bill_plan_value"]=>
NULL
["bill_type_id"]=>
NULL
["bill_plan_date"]=>
NULL
["bill_type"]=>
string(33) "Administration"
["parent_id"]=>
int(2)
["name"]=>
NULL
}
[0] is correct, but the following results return NULL users. I want all users and all accounts for users even if bill_plan is empty for user.
Second step is getting the last value
Need to get last value from bill_plans, where bill_plan_date <$ date (closest)
+3
source to share
1 answer
CROSS JOIN
SELECT b.*, bt.*, u.name
FROM bill_plans as b
RIGHT JOIN billing_types as bt ON bt.id = b.bill_type_id
CROSS JOIN users as u ON u.id = b.user_id
WHERE EXTRACT (MONTH FROM b.bill_plan_date) = $dateMonth
OR b.bill_plan_date IS NULL
AND bt.parent_id != 0
OR bt.parent_id IS NULL
0
source to share