2012-03-08 50 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