【发布时间】:2018-07-31 13:40:32
【问题描述】:
在同一张表下,我必须找到不同字段的总和,所以我使用下面的查询
select db.*, isnull(cb."8",0) as "8", db."PUR Total" - isnull(cb."8",0) as "9", eb.Item1, eb."PO Total"
from
(select b.t_dicl as Department, c.t_item as Item, sum( c.t_qstk )as "8"
from inforlndb.dbo.twhinr1109980 AS c INNER JOIN inforlndb.dbo.ttcemm1129980 AS b ON b.t_waid = c.t_cwar
where c.t_koor = 2 and c.t_kost = 3 and month(c.t_trdt) <= @aMonth - 1
group by c.t_item, b.t_dicl) as cb
full outer join
(select b.t_dicl as Department, c.t_item as Item, sum( c.t_qstk )as "PUR Total"
from inforlndb.dbo.twhinr1109980 AS c INNER JOIN inforlndb.dbo.ttcemm1129980 AS b ON b.t_waid = c.t_cwar
where c.t_koor = 2 and c.t_kost = 3 and month(c.t_trdt) <= @aMonth
group by c.t_item, b.t_dicl) as db
on cb.Item = db.Item
--Production order
full outer join
(select b.t_dicl as Department, c.t_item as Item, sum( c.t_qstk )as "8"
from inforlndb.dbo.twhinr1109980 AS c INNER JOIN inforlndb.dbo.ttcemm1129980 AS b ON b.t_waid = c.t_cwar
where c.t_koor = 1 and c.t_kost = 5 and month(c.t_trdt) <= @aMonth - 1
group by c.t_item, b.t_dicl) as ab
on cb.Item = ab.Item
full outer join
(select b.t_dicl as Department, c.t_item as Item1, sum( c.t_qstk )as "PO Total"
from inforlndb.dbo.twhinr1109980 AS c INNER JOIN inforlndb.dbo.ttcemm1129980 AS b ON b.t_waid = c.t_cwar
where c.t_koor = 1 and c.t_kost = 5 and month(c.t_trdt) <= @aMonth
group by c.t_item, b.t_dicl) as eb
on cb.Item = eb.Item1
样本输出为
Department Item PUR Total 8 9 Item1 PO Total
EV G00046301 25000 0 25000 NULL NULL
EV G00053001 10000 10000 0 G00053001 55
EV G00251701 4500 4500 0 G00251701 220
TF G01259901 200 0 200 NULL NULL
NULL NULL NULL 0 NULL NG707460AS 5
NULL NULL NULL 0 NULL G00046301 72
NULL NULL NULL 0 NULL G02280100 6
NULL NULL NULL 0 NULL NG707460BS 5
从输出中,您可以看到列 Item 和 Item1 下的不同行有两个相同的数据。如何合并它们?
抱歉代码比较乱,我还在学习中=="
【问题讨论】:
-
尝试使用内连接代替外连接。不匹配的行将被淘汰
-
我试过你的方法,但不是我所希望的。但谢谢。 :D @Hp_issei
-
您使用的是哪个DBMS 产品? “SQL”只是一种查询语言,而不是特定数据库产品的名称。
标签: sql select join group-by sum