我在表格中有此数据
IF OBJECT_ID('tempdb..#tmpTest') IS NOT NULL DROP TABLE #tmpTest;
SELECT calendar_week, id
INTO #tmpTest
FROM ( VALUES
(201106, 635),
(201106, 636),
(201106, 642),
(201106, 643),
(201107, 635),
(201107, 636),
(201107, 642),
(201107, 643),
(201211, 635),
(201211, 636),
(201211, 642),
(201211, 643),
(201211, 4421),
(201901, 635),
(201901, 636),
(201901, 642),
(201902, 635),
(201902, 636),
(201902, 642),
(201902, 4421)) AS t_insert (calendar_week, id);
我需要知道的是ID最匹配的日历周。没有数据是事先已知的。也就是说,calendar_week和id是随机的。因此,在这种情况下,它将是201106和201107,因为它们具有相同的ID,并且我们有两个日历周。有什么想法,如何实现?我的头是空的。非常感谢。
编辑:
如果我这样描述,也许更清楚:
Calendar week 201106 has these ids: 635, 636, 642, 643
Calendar week 201107 has these ids: 635, 636, 642, 643
因此,这两个日历周的ID是相同的,我可以用这些ID算两周。所有其他日历周都不同,并且仅计算一个。因此,201106和201107是获胜者,期望的输出是201106、201107。
答案 0 :(得分:0)
如果我理解正确,那么这就是group by
和order by
:
select top (1) with ties calendar_week, count(*)
from tmpTest
group by calendar_week
order by count(*) desc;
Here是db <>小提琴。
如果在平局时只需要一行,请删除with ties
。
答案 1 :(得分:0)
我用串联解决了这个问题。不太漂亮,但是可以用。
SELECT calendar_week
FROM
(
SELECT calendar_week,
(
SELECT CONVERT(VARCHAR(11), a.id) + ',' AS [text()]
FROM #tmpTest a
WHERE a.calendar_week = b.calendar_week
FOR XML PATH('')
) AS ids_concatenated
FROM #tmpTest b
GROUP BY calendar_week
) t
WHERE ids_concatenated =
(
SELECT TOP 1
ids_concatenated
FROM
(
SELECT calendar_week,
(
SELECT CONVERT(VARCHAR(11), a.id) + ',' AS [text()]
FROM #tmpTest a
WHERE a.calendar_week = b.calendar_week
FOR XML PATH('')
) AS ids_concatenated
FROM #tmpTest b
GROUP BY calendar_week
) t
GROUP BY ids_concatenated
ORDER BY COUNT(*) DESC
);