我的结果表中有多个计数查询

时间:2012-06-12 11:07:29

标签: sql sql-server

我有一张表mytable,其中有一个数字列myint。

我希望获得大于10,大于8但小于10,大于5但小于8的行数,并将它们显示在结果表中:

above 10 | above 8 below 10 | above 5 below 8
27       | 17               | 300  

我可以使用union all将它们垂直化。我必须使用连接来使它们水平吗?

3 个答案:

答案 0 :(得分:2)

SELECT 
    SUM (CASE WHEN myint > 10 THEN 1 ELSE 0 END) AS 'above 10',
    SUM (CASE WHEN myint BETWEEN 8 AND 9 THEN 1 ELSE 0 END) AS 'above 8 below 10',
    SUM (CASE WHEN myint BETWEEN 5 AND 7 THEN 1 ELSE 0 END) AS 'above 5 below 8'
FROM mytable

答案 1 :(得分:1)

如果要包含上限和下限,请将<更改为<=>更改为>=

select 
(select count(*) from myTable where myint > 10) as "above 10",
(select count(*) from myTable where myint > 8 and myint < 10) as "above 8 below 10",
(select count(*) from myTable where myint > 5 and myint <8) as "above 5 below 8"
from myTable 

答案 2 :(得分:1)

试试这个:

SELECT 
SUM(CASE WHEN myInt > 10 THEN 1 ELSE 0 END) AS '>10',
SUM(CASE WHEN myInt > 8 AND myInt < 10 THEN 1 ELSE 0 END) AS '(8-10)',
SUM(CASE WHEN myInt > 5 AND myInt < 8 THEN 1 ELSE 0 END) AS '(5-8)'
from    mytable
  • 请注意,您不会返回myInt = 8,因为它已从所有选项中排除。

这可能是最快的方法。