我有4张桌子。
T1
+------+-------+-------------+------+
| type | pcode | ccode | amnt |
+------+-------+-------------+------+
| s | 1 | 1801 | 1000 |
| s | 1 | 1801 | 2000 |
| s | 1 | 1801 | 3000 |
| s | 2 | 1802 | 1500 |
| s | 3 | 1802 | 2500 |
+------+-------+-------------+------+
T2
+-------+-------+
| btype | Ccode |
+-------+-------+
| 0 | 1701 |
| 0 | 1801 |
| 0 | 1801 |
| 1 | 1801 |
| 0 | 1802 |
| 1 | 1802 |
+-------+-------+
T3
+-------+------+-------+
| pcode | name | scode |
+-------+------+-------+
| 1 | pep | 1001 |
| 2 | coke | 1002 |
+-------+------+-------+
T4
+------+------+
| code | name |
+------+------+
| 1001 | pep |
| 1002 | coke |
+------+------+
我需要的结果集应满足以下条件。
如果bill type = 0,我需要t4.code,t4.name,sum(amount)为s1,如果billtype = 1,我需要sum(t1.amount)为s2
,结果集应为
+------+------+------+------+
| Code | name | s1 | s2 |
+------+------+------+------+
| 1001 | pep | 3000 | 3000 |
| 1002 | coke | 1500 | 2500 |
+------+------+------+------+
答案 0 :(得分:0)
You could use inner join and case for filter then values to sum
select t4.code, t4.name
, sum(CASE WHEN t2.btype=0 then T1.amnt else 0 end) s1
, sum(CASE WHEN t2.btype=1 then T1.amnt else 0 end) s2
from T4
INNER JOIN T3 on T3.scode = T4.code
INNER JOIN T1 on T3.pcode = T1.pcode
INNER JOIN T2 on T1.ccode = t2.ccode