我有一张表mytable,其中有一个数字列myint。
我希望获得大于10,大于8但小于10,大于5但小于8的行数,并将它们显示在结果表中:
above 10 | above 8 below 10 | above 5 below 8
27 | 17 | 300
我可以使用union all
将它们垂直化。我必须使用连接来使它们水平吗?
答案 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
这可能是最快的方法。