0

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

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

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

我可以使用union all. 我必须使用连接来使它们水平吗?

4

3 回答 3

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
于 2012-06-12T11:13:09.393 回答
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
  • 请注意,您不会返回 where myInt = 8 因为它被排除在所有选择之外。

这可能是最快的方法。

于 2012-06-12T11:19:13.393 回答
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 
于 2012-06-12T11:15:44.807 回答