我有一个表结构
表1
ID Hours Qty ProductID
1 2 1 100
1 3 5 200
2 6 6 100
2 2 2 200
如果productid是(1,2,3)那么我需要sum(数量*小时),如果productid在(200,300,400,500)那么我需要sum(qty)。
我写了这样的代码
select ID,case when productid in (1,2,3) then
SUM( qty * hrs)
when productid in (100,200,300) then SUM( qty ) end result1
from Prod group by id ,productid
但我不想按productid分组,我想在“IN子句”中传递它。如何实现它。
最佳答案
将 SUM()
移到 CASE WHEN
语句之外。
SELECT
ID,
SUM(case when productid in (1,2,3) then qty * hrs
when productid in (100,200,300) then qty
end) result1
FROM
Prod
GROUP BY
ID
关于sql - 通过隐藏列进行分组 - SQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9616732/