2010-10-13 143 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

相关问题