2012-03-08 62 views
2

我有一个表结构分组依据通过隐藏柱 - TSQL

表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)然后我需要总和(数量*小时),如果的productid在(200,300,400,500)那么我需要总和(数量)。

我写这样的

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子句”。如何去实现它。

回答

2

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 
0

假设你希望所有列加上您的查询的结果,你可以这样做:

select p.*, aux.result 
from Prod p 
inner join (select ID,case when productid in (1,2,3) then SUM(qty * hrs) 
          when productid in (100,200,300) then SUM(qty) 
         end as result 
      from Prod group by id ,productid) aux on aux.id = p.id 
+0

非常感谢你 – user1256813 2012-03-08 11:30:14