SELECT dbo.tblTrackNumber.CSTPONBR, dbo.tblTrackNumber.SOPNUMBE,
CASE WHEN dbo.tblTrackNumber.soptype = '2' THEN 'Order'
WHEN dbo.tblTrackNumber.soptype = '3' THEN 'Invoice'
WHEN dbo.tblTrackNumber.soptype = '4' THEN 'Return'
WHEN tblTrackNumber.soptype = '5' THEN 'BackOrder'
END AS SOPTYPE,
SUM(b.subtotal) AS subtotal, b.CSTPONBR AS CUSTPO
FROM [PSOPS].ps01.dbo.SOP30200 AS b RIGHT OUTER JOIN dbo.tblTrackNumber
ON b.CSTPONBR = dbo.tblTrackNumber.CSTPONBR
WHERE (b.VOIDSTTS <> '1') AND (dbo.tblTrackNumber.SOPTYPE = '3')
GROUP BY dbo.tblTrackNumber.CSTPONBR, dbo.tblTrackNumber.SOPNUMBE,
dbo.tblTrackNumber.SOPTYPE, b.CSTPONBR
结果:
小计值加倍(79.60应为39.80)。
CSTPONBR SOPNUMBE SOPTYPE subtotal CUSTPO
954664-PBM DTCI000649851 Invoice 79.60000 954664-PBM
954673-PBM DTCI000649852 Invoice 65.50000 954673 PBM
答案 0 :(得分:0)
这通常是因为join
正在生成其他行。建议的解决方案是在执行join
之前聚合数据:
SELECT t.CSTPONBR, t.SOPNUMBE,
(CASE WHEN t.soptype = '2' THEN 'Order'
WHEN t.soptype = '3' THEN 'Invoice'
WHEN t.soptype = '4' THEN 'Return'
WHEN t.soptype = '5' THEN 'BackOrder'
END) AS SOPTYPE,
SUM(b.subtotal) AS subtotal, b.CSTPONBR AS CUSTPO
FROM dbo.tblTrackNumber t LEFT JOIN
(SELECT b.cstponbr, SUM(b.substotal) as subtotal
FROM [PSOPS].ps01.dbo.SOP30200 b
GROUP BY b.cstponbr
) b
ON b.CSTPONBR = t.CSTPONBR
WHERE (b.VOIDSTTS <> '1') AND (t.SOPTYPE = '3')
GROUP BY t.CSTPONBR, t.SOPNUMBE, t.SOPTYPE, b.CSTPONBR;
我还做了一些其他改动:
right join
更改为left join
。大多数人发现left join
更容易关注(&#34;将所有行保留在第一个表格中#34;)。此外,您应该考虑以下因素:
id
是数字,请不要将常量括在单引号中进行比较。这是误导。字符串列的字符串常量。数字列的数字常量。b.CSTPONBR
。它应该与t.CSTPONBR
相同。如果记录匹配,您可能需要一个标记。group by
了。但是,如果没有样本数据,很难100%确定。