我很确定这是一件容易的事,但我是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作为基础,但可以访问更新的版本。过程是一组有限的值。
答案 0 :(得分: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
答案 1 :(得分: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