我完全展示了我在图片中的意思
请帮助我。
答案 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_ID
和dbo.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