2014-11-24 44 views
1

計數量值我有表:muximum如何計算相同的數字,並返回從每列

+-----+-----+-----+-----+ 
| ID | C1 | C2 | C3 | 
+-----+-----+-----+-----+ 
| 1 | 5 | 8 | 3 | 
| 2 | 7 | 4 | 7 | 
| 3 | 5 | 8 | 7 | 
| 4 | 8 | 2 | 7 | 
+-----+-----+-----+-----+ 

我想從中統計了每列返回一個數字。例如,在這樣的場景:

+----+----+----+ 
| C1 | C2 | C3 | 
+----+----+----+ 
| 5 | 8 | 7 | 
+----+----+----+ 

什麼是做到這一點的最好方法是什麼?

我寫了這個查詢,但它是一列只有

SELECT TOP 1 
    C1, 
    count(*) as Col1 
FROM [TableName] 
GROUP BY C1 
ORDER BY Col1 DESC 
+2

如果我有另一行怎麼辦:'5 | 5 | 2 | 1 |'?這將如何顯示?每列的逗號分隔值? – 2014-11-24 01:51:26

回答

1

試試這個:

創建示例數據

use tempdb 
create table temp(
    id int, 
    c1 int, 
    c2 int, 
    c3 int 
) 
insert into temp 
select 1, 5, 8, 3 union all 
select 2, 7, 4, 7 union all 
select 3, 5, 8, 7 union all 
select 4, 8, 2, 7 

SOLUTION

;with cte as(
    select c1 as val, 'c1' as col from temp union all 
    select c2 as val, 'c2' as col from temp union all 
    select c3 as val, 'c3' as col from temp 
) 
select 
    max(case when col = 'c1' then val end) as c1, 
    max(case when col = 'c2' then val end) as c2, 
    max(case when col = 'c3' then val end) as c3 
from (
    select 
     col, 
     val 
    from cte 
    group by col, val 
    having count(*) > 1 
)t 

DROP樣本數據

drop table temp 
+0

謝謝wewesthemenace。我對你的答案印象深刻。 – 2015-02-05 20:39:13

1

這裏是使用多個熱膨脹係數,一個用於每個列的一個解決方案。

;with cte1 
as 
(select row_number() over ( order by count(*) desc) as rn, 
     c1 
from Table1 
GROUP BY C1 
) 
,cte2 
as 
(select row_number() over ( order by count(*) desc) as rn, 
     c2 
from Table1 
GROUP BY C2 
) 
,cte3 
as 
(select row_number() over ( order by count(*) desc) as rn, 
     c3 
from Table1 
GROUP BY C3 
) 
select cte1.c1 as c1, 
     cte2.c2 as c2, 
     cte3.c3 as c3 
from cte1,cte2, cte3 
where cte1.rn = 1 
and cte2.rn =1 
and cte3.rn =1 
+0

令人敬畏的雷達。謝謝。 – 2015-02-05 20:37:17

相關問題