我有一張表格,里面有銷售資料。
結構是
| 產品編號 | 專案 | 價格 | 行動 |
|---|---|---|---|
| a1 | 10 | 100 | 1 |
| a1 | 6 | 60 | 0 |
| a1 | 5 | 50 | 2 |
| a2 | 3 | 30 | 1 |
| a2 | 4 | 40 | 0 |
| a2 | 1 | 70 | 2 |
當 Action 為 0 時,專案不計入 Sum。
當 Action 為 1 時,專案按 Sum 計數。
當 Action 為 2 時,這些專案是 Sum 的子結構。
所以,我想根據 Action 欄位對 Items 進行求和。
正確的結果必須是產品 a1 上的 5 個專案和產品 a2 上的 2 個專案。
你對我該怎么做有什么想法嗎?
uj5u.com熱心網友回復:
您可以將case運算式與聚合 ( group by, sum) 結合使用:
select ProductID,
sum(case Action
when 2 then Items
when 3 then -Items
else 0
end) SumItems
from Sales
group by ProductID;
uj5u.com熱心網友回復:
你可以試試這樣的
with x (ProductID,Items,Price,Action)
as
(
Select 'a1','10','100','1'
union all Select 'a1','6','60','0'
union all Select 'a1','5','50','2'
union all Select 'a2','3','30','1'
union all Select 'a2','4','40','0'
union all Select 'a2','1','70','2'
)
Select
y.ProductID,
sum(y.[Count]) as sum
from
(
Select
*,
case when Action = 0 then 0 when Action = 1 then items when Action = 2 then -1*items end as Count
from x
) y
GROUP by
y.ProductID
uj5u.com熱心網友回復:
我不知道其他資料庫,但這是 Access 的查詢。
select ProductID, sum(switch (Action = 2, -Items,action=1,Items)) as
SumItems from Sales group by ProductID
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/514539.html
標籤:毫秒访问
下一篇:訪問查詢以按百分比提高欄位值?
