SELECT
ShipDate, Stockroom, COLineNumber, CONumber, ShippedQty, ReversedQty,
CASE WHEN ReversedQty IS NULL THEN ShippedQty ELSE ReversedQty * - 1 END AS FinalShippedQty
FROM MyTable
WHERE CONumber = 'RAN-00001000'
这是我基于上述查询的当前输出:
ShipDate Stockroom CoLineNumber CONumber ShippedQty ReversedQty FinalShippedQty
-------- --------- ------------ ------------ ---------- ----------- ---------------
8/7/2013 01 1 RAN-00001000 10 *NULL* 10
8/7/2013 41 2 RAN-00001000 12 *NULL* 12
8/7/2013 41 3 RAN-00001000 24 *NULL* 24
8/7/2013 41 4 RAN-00001000 12 *NULL* 12
8/7/2013 41 4 RAN-00001000 *NULL* 2 -2
8/7/2013 01 5 RAN-00001000 50 *NULL* 50
8/7/2013 41 6 RAN-00001000 12 *NULL* 12
8/7/2013 41 6 RAN-00001000 *NULL* 3 -3
8/7/2013 41 6 RAN-00001000 *NULL* 3 -3
如上所述,CoLineNumber 4是两次,因为我们有一个原始条目,然后将数量反转2,然后CoLineNumber 6有三个条目用于相同的原因。我想对那些具有相同CoLineNumber且属于同一CONumber的行汇总FinalShippedQty列。这只是一个订单,但通常真正的提取物可能不少。
以下是我希望看到的输出:
ShipDate Stockroom CoLineNumber CONumber FinalShippedQty
-------- --------- ------------ ------------ ---------------
8/7/2013 01 1 RAN-00001000 10
8/7/2013 41 2 RAN-00001000 12
8/7/2013 41 3 RAN-00001000 24
8/7/2013 41 4 RAN-00001000 10
8/7/2013 01 5 RAN-00001000 50
8/7/2013 41 6 RAN-00001000 6
如果您有任何疑问或需要进一步说明,请与我们联系。再次记住,我拥有的表有数百个CoNumbers,但我只想为那些相同且属于特定CONumber的CoLineNumber总结FinalShippedQty。
编辑:我添加了第一次没有的Stockroom专栏。答案 0 :(得分:0)
我相信你只需要在查询中引入分组:
SELECT
ShipDate, Stockroom, COLineNumber, CONumber, ShippedQty, ReversedQty,
SUM(CASE WHEN ReversedQty IS NULL THEN ShippedQty ELSE ReversedQty * - 1 END) AS FinalShippedQty
FROM MyTable
WHERE CONumber = 'RAN-00001000'
GROUP BY
ShipDate, Stockroom, COLineNumber, CONumber
;
另请注意,您的CASE表达式可以使用COALESCE重写:
SELECT
ShipDate, Stockroom, COLineNumber, CONumber,
SUM(COALESCE(-ReversedQty, ShippedQty)) AS FinalShippedQty
FROM MyTable
WHERE CONumber = 'RAN-00001000'
GROUP BY
ShipDate, Stockroom, COLineNumber, CONumber
;