我需要来自2列的TOP 1字符串,该值应按出现次数和名称递减的顺序返回。这是在SQL-Server。
这是一个示例表:
------------------------------
| 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 |
----------------------------
答案 0 :(得分: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
获取最常用的名称并首先按字母顺序选择:
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
答案 1 :(得分:2)
从SQL 2005开始,您可以使用UNPIVOT:
-- 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
答案 2 :(得分: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