T-SQL如何从结果集中获取最常见的值

时间:2016-05-27 08:52:51

标签: sql-server-2012

尝试获得结果集中最常见日期的单个结果:

SELECT col1, col2,  
(SELECT MIN(CONVERT(VARCHAR,[date], 103)) FROM TABLE )  AS [Date]
FROM TABLE WHERE [Date] BETWEEN '20160101' AND '20160131'

结果:

enter image description here

所以我只想要15/01/2016。我知道我需要使用子查询和计数,并尝试了许多不同的解决方案,作为一个新手,我发现子查询比JOIN特别相关的嵌套子查询更难以理解。

1 个答案:

答案 0 :(得分:3)

date分组,按count descending排序并选择top 1

select top 1 with ties [date] 
from table 
where [date] between '20160101' and '20160131'
group by [date]
order by count(*) desc
如果某些日期的最大数量可能相同,

with ties将选择多个日期。