0

我有一张这样的桌子:

   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

如何从嵌套查询中获得上述结果?任何帮助都会非常有用。

提前非常感谢。苏维

4

3 回答 3

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

于 2013-09-06T13:39:34.963 回答
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)

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

于 2013-09-06T13:35:53.117 回答
-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 号的计数。

于 2013-09-06T13:33:47.990 回答