联盟都在同一张桌子上

时间:2014-04-23 20:11:37

标签: sql sql-server

必须有更好的方法来做任何有想法的人。有一个表,我有8列我需要选择所有的列一个在彼此的顶部和每个选定的列我需要计算相同的项目数

SELECT  Col1, count(*) 'Selected'
FROM  [Table]  
group by temp_id,Col1
UNION ALL
SELECT    Col2,count(*)
FROM  [Table]  
group by temp_id,Col2
having   len(ltrim(rtrim(Col2)))<>0
UNION ALL
SELECT    Col3,count(*)
FROM  [Table]  
group by temp_id,Col3
having   len(ltrim(rtrim(Col3)))<>0
union all
SELECT    Col4,count(*)
FROM  [Table]  
group by temp_id,Col4
union all
SELECT    Col5,count(*)
FROM  [Table]  
group by temp_id,Col5
having   len(ltrim(rtrim(Col5)))<>0
union all
SELECT    Col6,count(*)
FROM  [Table]  
group by temp_id,Col6
having   len(ltrim(rtrim(Col6)))<>0
union all
SELECT    Col7,count(*)
FROM  [Table]  
group by temp_id,Col7
having   len(ltrim(rtrim(Col7)))<>0
union all
SELECT    Col8,count(*)
FROM  [Table]  
group by temp_id,Col8
having   len(ltrim(rtrim(Col8)))<>0

1 个答案:

答案 0 :(得分:1)

有。它被称为分组集(并记录为here)。在你的情况下,你可以做这样的事情(前三列的例子):

select coalesce(col1, col2, col3), count(*) as Selected
from [table]
group by grouping sets ((temp_id, col1), (temp_id, col2), (temp_id, col3));

您在每列上使用length()trim()的条件 - 您应该使用having子句处理它。