SQL - 一列中最常见(重复)的值

时间:2014-02-08 08:24:27

标签: c# sql sql-server

我完全展示了我在图片中的意思

enter image description here

请帮助我。

2 个答案:

答案 0 :(得分:2)

试试这个:

SELECT TOP(1) WITH TIES
       p.ID, p.Destination, COUNT(*) AS CountOfTrips
FROM   dbo.tblPath p INNER JOIN dbo.tblTrip t
ON     p.ID = t.Path_ID
GROUP BY p.ID, p.Destination
ORDER BY CountOfTrips DESC

注意#1:TOP WITH TIES

注意#2:TOP(1)TOP(1) WITH TIES之间的差异:

SELECT  TOP(1)  
        src.Name, src.Cnt
FROM    (
    SELECT 'A', 1 UNION ALL 
    SELECT 'B', 2 UNION ALL SELECT 'C', 2 UNION ALL 
    SELECT 'D', 1 UNION ALL SELECT 'E', 1
) src(Name,Cnt)
ORDER BY src.Cnt DESC;
/*
Name Cnt
---- ---
B    2
*/

VS

SELECT  TOP(1) WITH TIES 
        src.Name, src.Cnt
FROM    (
    SELECT 'A', 1 UNION ALL 
    SELECT 'B', 2 UNION ALL SELECT 'C', 2 UNION ALL 
    SELECT 'D', 1 UNION ALL SELECT 'E', 1
) src(Name,Cnt)
ORDER BY src.Cnt DESC;
/*
Name Cnt
---- ---
B    2
C    2
*/

注意#2:您忘记了p.ID = t.Path_IDdbo.tblPath之间的联接谓词/条件(dbo.tblTrip)。在SQL Server中,使用ANSI SQL 92样式连接是不可能的,因为连接谓词对于INNER / LEFT / RIGHT / FULL JOIN是必需的。

答案 1 :(得分:0)

对于未来的访客: 本规范解决了我的问题:

SELECT TOP(1) WITH TIES
       p.ID, p.Destination, COUNT(*) AS CountOfTrips
FROM   dbo.tblPath p INNER JOIN dbo.tblTrip t
ON     p.ID = t.Path_ID
GROUP BY p.ID, p.Destination
ORDER BY CountOfTrips DESC