我在尝试弄清楚如何创建查询时遇到问题... 假设我们有两个这样的表:
TABLE A
id - box1_id - box1count - box2_id - box2_count
1 - 1 - 100 - 2 - 111
2 - 2 - 222 - NULL - NULL
3 - 2 - 333 - 3 - 1000
TABLE B
id_box - box_Name
1 - HELLO
2 - TEST
3 - HELP
我想编写一个查询类似的查询:
id_box - box_Name - box_sumcount
1 - HELLO - 100
2 - TEST - 666
3 - HELP - 1000
box_sumcount是box1_count或box2_count的总和,基于box1_id或box2_id等于id_box ...
答案 0 :(得分:4)
SELECT TableB.id_Box,TableB.Boxname, Sum(BC.BoxCount)
FROM TableB
INNER JOIN
(SELECT box1_id as boxid, box1Count as boxCount
UNION
SELECT box2_id as boxid, box2Count as boxCount
) BC
ON (TableB.id_box=BC.Boxid)
GROUP BY TableB.id_Box, TableB.Boxname