更好地查询 "Select" 内的 "Select"

Better Query for "Select" inside "Select"

有没有更好更短的方法来生成如下 SQL 查询? 更好的可能是更短的查询 or/and 最快的性能影响 到服务器

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

在小数据上使用这个查询似乎没有什么区别,但是当我在大数据上使用这个查询时,查询变得很慢。 (我有超过 600k 行)

目前我有table如下图

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

试试这个:

简单 COUNT(DISTINCT ....) 会帮助你。

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