我有这张桌子
我想将它分组为
ProductID Purchased Sold
------------------------------------
1 235 0.00
2 125 0.00
3 55 24.00
此处已购买=(IsCreditor<> 0)
我试过这个
SELECT
ProductID,
Max (TotalQty) As Purchased,
Min(TotalQty) As Sold
FROM
TestTable
GROUP BY
ProductID
仅当产品同时具有IsCreditor = 0和IsCreditor = 1
时,它才有效该表是存储过程的一小部分
在此表中,对于productid = 1,如果没有购买或出售,它将不会出现,如果它被购买,它会显示一个数量和IsCreditor = 1,如果它被出售,它会显示数量为一行IsCreditor = 0,另一行isCreditor = 1
答案 0 :(得分:1)
添加CASE语句以分隔购买和出售的商品
SELECT
ProductID,
SUM(Case When IsCreditor = 1 then TotalQty else 0 end) AS [TotalPurchase],
SUM(Case When IsCreditor = 0 then TotalQty else 0 end) AS [TotalSale]
FROM
TestTable
GROUP BY
ProductID