sql server,表中许多列的聚合(count)

时间:2015-05-20 07:26:49

标签: sql-server

我有一张表,我已将其简化为以下内容。它实际上扩展到Type60

   Number     | Type1     | Type2     | Type3     | Type4
   ------------------------------------------------------
   1          | 1         | 1         | 1         | 0
   2          | 1         | 1         | 1         | 0
   3          | 1         | 1         | 1         | 0   
   4          | 0         | 2         | 0         | 1   
   5          | 0         | 2         | 1         | 0   
   6          | 0         | 2         | 0         | 1
   7          | 1         | 1         | 1         | 0
   8          | 1         | 1         | 0         | 1
   9          | 1         | 2         | 1         | 0
   10         | 0         | 2         | 0         | 1

我想要的输出如下(扩展到Name60)

   Name     | Value     | CountOfValue 
   -----------------------------------
   Name1    | 0         | 4 
   Name1    | 1         | 6    
   Name2    | 1         | 5 
   Name2    | 2         | 5 
   Name3    | 0         | 6 
   Name3    | 1         | 4 
   Name4    | 0         | 4 
   Name4    | 1         | 6 

到那儿,我一直在做:

select 'Name1' as Name, Type1, Count(Number)
from table1
group by Type1

union

select 'Name2' as Name, Type2, Count(Number)
from table1
group by Type2

union

select 'Name3' as Name, Type3, Count(Number)
from table1
group by Type3

union

select 'Name4' as Name, Type4, Count(Number)
from table1
group by Type4

直到Name60等

这需要一段时间才能运行,

有没有更有效率(更快)的方法来做同样的事情有人知道吗?

谢谢,加里

1 个答案:

答案 0 :(得分:0)

你可以试试UNPIVOT。

SELECT Name, [values] AS Value, Count(*) AS CountOfValue
FROM
(
    SELECT REPLACE([Type], 'Type', 'Name') AS Name, [values]
    FROM #testPivot
    UNPIVOT ([values] FOR [type] IN 
            (Type1, Type2, Type3, Type4) -- ETC to Type60
    ) AS unpvt
) AS test
GROUP BY Name, [values]
ORDER BY Name, Value

你仍然需要在UNPIVOT中输入所有Type1到Type 60。查看PIVOT and UNPIVOT