2012-04-16 41 views
-1

我需要2列中的TOP 1字符串,該值應按照出現次數和名稱下降順序返回。這是在SQL-Server中。我如何從2列的UNION獲得TOP 1顯示值(按1位數計數和名稱desc)

下面是一個例子表:

------------------------------ 
| Column1 | Column2 | 
------------------------------ 
|  John  | Michael | 
------------------------------ 
| Thomas | John  | 
------------------------------ 
| Martin | Rick  | 
------------------------------ 
| David  | Thomas | 
------------------------------ 
|  John  | Martin | 
------------------------------ 

產生的順序應該是什麼樣子:

---------------------------- 
| Column1 | COUNT | 
---------------------------- 
|  John  |  3  | 
---------------------------- 
| Martin |  2  | 
---------------------------- 
| Thomas |  2  | 
---------------------------- 
|  David |  1  | 
---------------------------- 
| Michael |  1  | 
---------------------------- 
|  Rick  |  1  | 
---------------------------- 

的結果應該是什麼樣子:

---------------------------- 
| Column1 | COUNT | 
---------------------------- 
|  John  |  3  | 
---------------------------- 

回答

3
select top 1 c, count(*) [Count] 
from 
(
    select column1 c 
    from ATable 
    union all 
    select column2 
    from ATable 
) a 
group by c 
order by count(*) desc 

要獲得最常用的名稱和按字母順序選擇f IRST其中:

select top 1 c, count(*) [Count] 
from 
(
    select column1 c 
    from ATable 
    union all 
    select column2 
    from ATable 
) a 
group by c 
order by count(*) desc, c 

如果你想要做相同的,但只有一個列:

select top 1 column1, count(*) [Count] 
    from ATable 
group by column1 
order by count(*) desc, column1 
+0

這對我有效。謝謝。 – Alternatex 2012-04-16 12:48:30

0
CREATE TABLE #t (Column1 nvarchar(50), Column2 nvarchar(50)) 
INSERT INTO #t (Column1, Column2) 
VALUES ('John', 'Michael') 
,('Thomas', 'John') 
,('Martin', 'Rick') 
,('David', 'Thomas') 
,('John', 'Martin') 



;WITH cte (Column1) 
AS 
(
    SELECT Column1 
    FROM #t 

    UNION ALL 

    SELECT Column2 
    FROM #t 
) 



SELECT TOP 1 
     Column1 
     ,COUNT(*) as [COUNT] 
FROM cte 
GROUP BY Column1 
ORDER BY [COUNT] DESC 
2

您可以使用UNPIVOT,作爲2005年的SQL:

-- Example Data 
DECLARE @Data TABLE (Column1 VARCHAR(10), Column2 VARCHAR(10)) 
INSERT @Data VALUES ('A', 'B'), ('B', 'A'), ('C', 'A'), ('D', 'E'), ('A', 'D') 

SELECT TOP 1 Name, COUNT(*) 
FROM @Data d 
    UNPIVOT (Name FOR Col IN (Column1, Column2)) AS unpvt 
GROUP BY Name 
ORDER BY COUNT(*) DESC 
+0

+1,UNPIVOT是可愛的:-) – 2012-04-16 12:43:38