2010-10-13 142 views
2

我相當確定這是一件容易的事情,但我是SQL新手,所以要溫和。如果我想編寫一個查詢,將每個進程編號的總髮生次數加起來,並將這些值存儲到新列中,我該怎麼做?我認爲一些混合物(清楚...)可能會把它弄清楚,但我不確定。查看結果表以瞭解我在找什麼。選擇一組不同的值並將它們分別計入新列

 
Order_Table: 

order_number  process 
     100   8 
     100   7 
     100   7 
     100   6 
     100   5 
     105   6 
     105   2 
     105   4 

Results: 

order_num NumOfEight NumOfSeven NumOfSix NumOfFive NumOfFour NumOfTwo 
     100    1   2   1   1   0   0 
     105    0   0   1   0   1   1 


更新:我使用SQL 2005作爲基礎,但可以訪問更新的版本。過程是一組有限的值。

回答

2

假設的SQL Server 2005+可以使用PIVOT

SELECT 
     order_num, [8] AS NumOfEight, [7] AS NumOfSeven /* etc. etc.*/ 
FROM 
     (SELECT order_number AS order_num, process FROM Order_Table) p 
PIVOT 
     (COUNT(process) FOR process IN ([8],[7] /* etc. etc.*/)) pvt 
+0

這是一個優雅的解決方案。 – npeterson 2010-10-13 14:57:56

1
select order_num, 
     sum(case when process = 8 then 1 else 0 end) as NumOfEight, 
     sum(case when process = 7 then 1 else 0 end) as NumOfSeven, 
     sum(case when process = 6 then 1 else 0 end) as NumOfSix 
     /* Repeat as many times as needed */ 
    from Order_Table 
    group by order_num 
+0

三江源這個答案也。這更接近我的原始嘗試,但我並沒有考慮將值設爲1或0並對它進行求和。 – npeterson 2010-10-13 14:59:11

+1

@npeterson:很高興幫助。你可以用贊成票(兩個答案)來說「謝謝你」。 :-) – 2010-10-13 15:06:05

相關問題