嵌套SQL查询:如何根据不同条件对相同元素进行多次计数

时间:2013-09-06 13:28:15

标签: sql

我有一张这样的表:

   Server     CompliancePercentage
   A          25
   B          15
   C          45
   D          75
   E          17
   F          82

我希望通过以下方式从单个查询获得结果:

   Conformity%        00-20   20-40   40-60  60-80   80-100
   Server Count       2       1          1     1      1

如何从嵌套查询中获得上述结果? 任何帮助都会很棒。

提前多多感谢。 苏维

3 个答案:

答案 0 :(得分:2)

您可以使用带有CASE表达式的聚合函数来获得结果:

select
  'ServerCount' Conformity,
  count(case when CompliancePercentage >= 0 and CompliancePercentage <20 then 1 end) Per00_19,
  count(case when CompliancePercentage >= 20 and CompliancePercentage <40 then 1 end) Per20_39,
  count(case when CompliancePercentage >= 40 and CompliancePercentage <60 then 1 end) Per40_59,
  count(case when CompliancePercentage >= 60 and CompliancePercentage <80 then 1 end) Per60_79,
  count(case when CompliancePercentage >= 80 and CompliancePercentage <100 then 1 end) Per80_100
from yourtable;

请参阅SQL Fiddle with Demo

答案 1 :(得分:1)

假设下表:

create table dummyTable
(
    srv char(1),
    comp int
)

您可以写出类似于

的查询
select 
    [00-19] = (SELECT COUNT(1) FROM dummyTable where comp between 0 and 19),
    [20-39] = (SELECT COUNT(1) FROM dummyTable where comp between 20 and 39)

如果您的表有大量记录(即&gt; 1M),您可能需要考虑在合规百分比列的表中添加非聚集索引,以避免一堆表扫描。

答案 2 :(得分:-1)

这样的事情对你有用:

SELECT
    ( COUNT(id) FROM table WHERE id > 1 ) AS id_gt_1,
    ( COUNT(id) FROM table WHERE id > 100 ) AS id_gt_100

在这里,我匹配的标准只是ID号的计数。