今天在社区看到一个问题如何返回 统计数值,比较简单,分享一下写法:
--测试数据
if not object_id(N'Tempdb..#T') is nulldrop table #T
Go
Create table #T([name] nvarchar(21),[year] nvarchar(21),[time] nvarchar(22))
Insert #T
select N'王','2019',N'03' union all
select N'王','2019',N'05' union all
select N'王','2019',N'06' union all
select N'王','2019',N'07' union all
select N'羌','2019',N'08' union all
select N'羌','2019',N'10' union all
select N'羌','2019',N'11' union all
select N'阿','2020',N'01' union all
select N'吧','2020',N'02' union all
select N'吧','2020',N'03' union all
select N'吧','2020',N'04' union all
select N'想','2020',N'06' union all
select N'想','2020',N'07' union all
select N'想','2020',N'08'
Go
--测试数据结束
SELECT *
FROM
(SELECT year, COUNT(DISTINCT name) AS namecount FROM #T GROUP BY year) t
WHERE t.namecount <= 2;
结果: