-1

我需要 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     |
----------------------------
4

3 回答 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

要获得最常用的名称并按字母顺序选择其中的第一个:

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
于 2012-04-16T12:35:17.553 回答
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
于 2012-04-16T12:39:25.370 回答
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
于 2012-04-16T12:35:26.443 回答