基于其他已发布的答案。
这两个都会产生正确的值:
select distributor_id,
count(*) total,
sum(case when level = 'exec' then 1 else 0 end) ExecCount,
sum(case when level = 'personal' then 1 else 0 end) PersonalCount
from yourtable
group by distributor_id
SELECT a.distributor_id,
(SELECT COUNT(*) FROM myTable WHERE level='personal' and distributor_id = a.distributor_id) as PersonalCount,
(SELECT COUNT(*) FROM myTable WHERE level='exec' and distributor_id = a.distributor_id) as ExecCount,
(SELECT COUNT(*) FROM myTable WHERE distributor_id = a.distributor_id) as TotalCount
FROM myTable a ;
但是,性能却大不相同,随着数据量的增长,这显然会更加相关。
我发现,假设没有在表上定义索引,使用 SUM 的查询将进行一次表扫描,而使用 COUNT 的查询将进行多次表扫描。
例如,运行以下脚本:
IF OBJECT_ID (N't1', N'U') IS NOT NULL
drop table t1
create table t1 (f1 int)
insert into t1 values (1)
insert into t1 values (1)
insert into t1 values (2)
insert into t1 values (2)
insert into t1 values (2)
insert into t1 values (3)
insert into t1 values (3)
insert into t1 values (3)
insert into t1 values (3)
insert into t1 values (4)
insert into t1 values (4)
insert into t1 values (4)
insert into t1 values (4)
insert into t1 values (4)
SELECT SUM(CASE WHEN f1 = 1 THEN 1 else 0 end),
SUM(CASE WHEN f1 = 2 THEN 1 else 0 end),
SUM(CASE WHEN f1 = 3 THEN 1 else 0 end),
SUM(CASE WHEN f1 = 4 THEN 1 else 0 end)
from t1
SELECT
(select COUNT(*) from t1 where f1 = 1),
(select COUNT(*) from t1 where f1 = 2),
(select COUNT(*) from t1 where f1 = 3),
(select COUNT(*) from t1 where f1 = 4)
突出显示 2 个 SELECT 语句并单击 Display Estimated Execution Plan 图标。您会看到第一个语句将执行一次表扫描,第二个语句将执行 4 次。显然,一次表扫描优于 4。
添加聚集索引也很有趣。例如
Create clustered index t1f1 on t1(f1);
Update Statistics t1;
上面的第一个 SELECT 将执行单个聚集索引扫描。第二个 SELECT 将执行 4 次聚集索引搜索,但它们仍然比单个聚集索引扫描更昂贵。我在一个有 800 万行的表上尝试了同样的事情,而第二个 SELECT 仍然要贵得多。