sql - 计算特定范围sql server的记录数

标签 sql sql-server coldfusion

我正在尝试编写一个查询来根据多个不同范围来计算记录数。

我成功地使用了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 serializedJSON 文件。因此,在数据库中,下面的所有内容都工作得很好,但是查询的冷融合查询不支持 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 <= 30000col1 > 30000 and col1 <= 45000为条件。但是,我不会更改它们,因为上面是原始问题的措辞(也许 1500130001 有一些特别之处)。

关于sql - 计算特定范围sql server的记录数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17813330/

相关文章:

sql - 如何插入只有一个 IDENTITY 列的表?

php - 在 mysql 或 sql server 中连接三个具有循环关系的表

ajax - 使用 ColdFusion CFC 时 JQuery 出现无效 JSON 错误,即使返回看似正确的 JSON

php - 在 PHP 中向 MYSQL 数据库添加记录不起作用

python - Django:更复杂的唯一性约束?

sql - ORA-06502 : PL/SQL: numeric or value error: character string buffer too small

sql - SQL Server 2008 中 "CASE"子句内的 "WHERE"语句

post - ColdFusion CFHTTP Post 正在执行第二个 GET 请求

coldfusion - 从 ColdFusion 8 获取 CLOB 数据

sql - 数据库 tbl 上的 dplyr 函数是本地执行还是远程执行?