我正在尝试编写一个查询来根据多个不同范围来计算记录数。
我成功地使用了union
,但我觉得还有更好的方法。
这是我所做的:
select count(col1) as range1
from tbl1
where col1 <= 15000
union
select count(col1) as range2
from tbl1
where col1 > 15001 and col1 <= 30000
union
select count(col1) as range3
from tbl1
where col1 > 30001 and col1 <= 45000
etc...
我正在使用 sql server 2008。就像我上面所说的那样,我确信有更好的方法可以做到这一点,也许是这样的:sql count ,
编辑:是的,数据库是 sql 2008,下面的答案完全按照需要工作。我忘了提及,我实际上正在读取一个通过 Coldfusion serializeJSON
serialized
的 JSON
文件。因此,在数据库中,下面的所有内容都工作得很好,但是查询的冷融合查询不支持 CASE 语句,或者看起来不支持。
最佳答案
一种方法是使用条件求和(对于单独列中的值):
select sum(case when col1 <= 15000 then 1 else 0 end) as range1,
sum(case when col1 > 15001 and col1 <= 30000 then 1 else 0 end) as range2,
sum(case when col1 > 30001 and col1 <= 45000 then 1 else 0 end) as range3
from tbl1;
另一种方法是 group by
(对于单独行上的值):
select (case when col1 <= 15000 then 'range1'
when col1 > 15001 and col1 <= 30000 then 'range2'
when col1 > 30001 and col1 <= 45000 then 'range3'
else 'other'
end) as range, count(*) as cnt
from tbl1
group by (case when col1 <= 15000 then 'range1'
when col1 > 15001 and col1 <= 30000 then 'range2'
when col1 > 30001 and col1 <= 45000 then 'range3'
else 'other'
end);
我经常使用这种形式的子查询:
select range, count(*)
from (select t.*,
(case when col1 <= 15000 then 'range1'
when col1 > 15001 and col1 <= 30000 then 'range2'
when col1 > 30001 and col1 <= 45000 then 'range3'
else 'other'
end) as range
from tbl1
group by range;
这样,range
的定义只出现一次。
编辑:
以上均使用OP中的逻辑。然而,上述逻辑遗漏了 15001
的值。和30001
。我的猜测是,OP 的真正含义是 col1 > 15000 and col1 <= 30000
和col1 > 30000 and col1 <= 45000
为条件。但是,我不会更改它们,因为上面是原始问题的措辞(也许 15001
和 30001
有一些特别之处)。
关于sql - 计算特定范围sql server的记录数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17813330/