我有一个表 mytable,其中有一个数字列 myint。
我希望获得高于 10、高于 8 但低于 10、高于 5 但低于 8 的行数,并将它们显示在结果表中:
above 10 | above 8 below 10 | above 5 below 8
27 | 17 | 300
我可以使用union all
. 我必须使用连接来使它们水平吗?
我有一个表 mytable,其中有一个数字列 myint。
我希望获得高于 10、高于 8 但低于 10、高于 5 但低于 8 的行数,并将它们显示在结果表中:
above 10 | above 8 below 10 | above 5 below 8
27 | 17 | 300
我可以使用union all
. 我必须使用连接来使它们水平吗?
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
尝试这个:
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
这可能是最快的方法。
如果要包括上限或下限,请更改<
为<=
或>
>=
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