我有一个(简化的)表,其结构如下:
Table: ItemData
PK | ScanCode | StoreFK | Retail | ReceiptAlias
1 | 100101 | 1 | 4.99 | Milk
4 | 100101 | 2 | 4.99 | Milk
7 | 100101 | 3 | 0.99 | Milk
2 | 100102 | 1 | 6.99 | Eggs
5 | 100102 | 2 | 6.99 | Eggs
8 | 100102 | 3 | 6.99 | Eggs
3 | 100103 | 1 | 7.99 | Bread
6 | 100103 | 2 | 8.99 | Bread
9 | 100103 | 3 | 9.99 | Bread
我可以使用以下SQL查询来获取以下返回结果,该结果显示在一个或多个商店中具有不同零售的所有商品:see this previously asked question
SQL查询:
SELECT im.INV_ScanCode AS ScanCode,
name.ItemData AS im
GROUP BY ScanCode, Receipt_Alias
HAVING COUNT(DISTINCT im.Retail) > 1
ORDER BY ScanCode
当前返回结果:
ScanCode | Receipt_Alias
100101 | Milk
100103 | Bread
我想在一个或多个商店退回所有零售店铺的商品 AND 在每个商店位置的零售商店:
所需的退货结果:
ScanCode | Receipt_Alias | Str_1 | Str_2 | Str_3
100101 | Milk | 4.99 | 4.99 | 0.99
100103 | Bread | 7.99 | 8.99 | 9.99
如何更改我的SQL查询以在每个商店位置包含零售?
答案 0 :(得分:2)
SELECT ScanCode as ItemID,
ReceiptAlias,
MAX(CASE WHEN StoreFK = 1 THEN Retail ELSE NULL END) Store_1,
MAX(CASE WHEN StoreFK = 2 THEN Retail ELSE NULL END) Store_2,
MAX(CASE WHEN StoreFK = 3 THEN Retail ELSE NULL END) Store_3
FROM ItemData
GROUP BY ScanCode, ReceiptAlias
HAVING COUNT(DISTINCT Retail) > 1