在“选择”中更好地查询“选择”

时间:2019-12-06 02:51:17

标签: sql-server sql-server-2008 sql-server-2008-r2

是否有更好和更短的方法来生成如下所示的SQL查询? 较短的查询或/和影响最快的性能到服务器

可能会更好
select TowerID, COUNT(TowerID) as 'QTY'
from (
    select TowerID, [USER] as 'QTY'
    from ColoEngDBLocal..Carriers
    where [Status] not like '%removed%'
    group by TowerID, [USER]
) as a
group by TowerID
order by TowerID

当我在小数据上使用此查询时似乎没有什么区别,但是当我在大数据上使用此查询时,查询变慢。 (我有超过60万行)

目前我有如下表

enter image description here

注意:我正在使用SQL Server 2008 R2

1 个答案:

答案 0 :(得分:2)

尝试一下:

简单的 COUNT(DISTINCT ....)将为您提供帮助。

select TowerID, COUNT(DISTINCT [USER]) as 'QTY'
from ColoEngDBLocal..Carriers
where [Status] not like '%removed%'
group by TowerID
ORDER BY TowerId