我有一个签到表,其中包含流动的列:
PK CheckInID int
PersonID int
CheckInDate smalldatetime
我正在尝试创建一个查询,该查询为我提供了最常见的人员排行榜前三名。
例如:
personID 1 was
18 times together with personID 3
13 times together with personID 9
11 times together with personID 4
在C#中实现这个对我来说并不是一个问题,但我想创建一个存储过程,而TSQL实际上并不是我强大的一面。
答案 0 :(得分:1)
假设日期是指定者:
SELECT TOP 3 PersonId, COUNT(*) cnt
FROM your_table
WHERE CheckInDate IN (SELECT CheckInDate
FROM your_table
WHERE PersonId = ?)
AND PersonId <> ? -- do not count the same person
GROUP BY PersonId
ORDER BY cnt DESC;
答案 1 :(得分:1)
更快的方式(没有子查询,没有&#34; IN&#34;语句):
SELECT TOP 3 T2.PersonId
, SUM(1) AS NB_TIME_CHECKED_IN_WITH_XXX
FROM your_table AS T1
INNER JOIN your_table AS T2 ON (T1.[PK CheckInID]=T2.[PK CheckInID] AND T2.PersonId <> XXX)
WHERE T1.PersonId = XXX
GROUP BY PersonId
ORDER BY NB_TIME_CHECKED_IN_WITH_XXX DESC;