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

Rob*_*b M 4 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...
Run Code Online (Sandbox Code Playgroud)

我正在使用sql server 2008.就像我上面所述,我很肯定有更好的方法来做到这一点,也许是这样的:sql count,

编辑:是的,数据库是sql 2008,下面的答案完全按照需要工作.我忘了提到我实际上是在读一个通过coldfusion 的JSON文件.所以在db中,下面的所有内容都能正常工作,但查询的coldfusion查询不支持该语句,或者它看起来不支持.serializedserializeJSONCASE

Gor*_*off 10

一种方法是使用条件求和(对于单独列中的值):

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;
Run Code Online (Sandbox Code Playgroud)

另一种方法是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);
Run Code Online (Sandbox Code Playgroud)

我经常使用子查询来表示这种形式:

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;
Run Code Online (Sandbox Code Playgroud)

这样,定义range只出现一次.

编辑:

以上都使用了OP的逻辑.但是,上述逻辑错过了15001和的值30001.我的猜测是OP确实意味着col1 > 15000 and col1 <= 30000col1 > 30000 and col1 <= 45000条件.但是,我不会改变他们,因为上面是原来的问题是如何措辞(也许有一些特别的1500130001).


gve*_*vee 6

就我个人而言,我更喜欢使用派生(或物理)表来存储我的范围边界,然后我将其连接回来以找到我的结果。

我认为代码更简单,并且如果需要的话更容易扩展

有点像这样:

; WITH ranges (lbound, ubound) AS (
  SELECT 0, 1500
  UNION ALL SELECT 1500, 3000
  UNION ALL SELECT 3000, 4500
)
SELECT ranges.lbound
     , ranges.ubound
     , Count(your_table.value) As turtle
FROM   ranges
 LEFT
  JOIN your_table
    ON your_table.value >= ranges.lbound
   AND your_table.value <  ranges.ubound
GROUP
    BY ranges.lbound
     , ranges.ubound
Run Code Online (Sandbox Code Playgroud)