完成独特计数时的TSQL限制结果

时间:2016-02-13 00:49:27

标签: sql sql-server tsql

我试图限制此查询以仅返回来自非重复计数的top10结果。我仍然希望它完成对所有内容的计数,但将结果限制在前10名mycount

谢谢

SELECT
   distinct count(TagName) as mycount
  ,[Area]
  ,[TagName]
  ,[Description]


  FROM [A2ALMDB].[dbo].[v_AlarmHistory]
  where value = 'true' and 
  eventstamp between '20160203' and '20160210'
  group by area,TagName, Description
  order by mycount desc

1 个答案:

答案 0 :(得分:2)

您是否尝试过top 10

SELECT TOP 10 count(TagName) as mycount, [Area], [TagName], [Description]
FROM [A2ALMDB].[dbo].[v_AlarmHistory]
WHERE value = 'true' and 
      eventstamp between '20160203' and '20160210'
GROUP BY [Area], [TagName], [Description]
ORDER BY mycount DESC;

构建查询的适当方法是使用GROUP BY,而不是SELECT DISTINCT