在SQL Server中累积计数计算

时间:2010-01-16 00:29:29

标签: sql-server

如果我有一个包含2列的表 - ID,钱。 我想做一个查询,找出有多少ID的钱少于100,200,300,......,10000 我应该如何在SQL Server中执行此操作?我需要使用变量吗?

3 个答案:

答案 0 :(得分:1)

假设id是一个关键列,请尝试:

Select Case When money < 100 Then 'LT100'
            When money < 200 Then 'From100To199'
            When money < 300 Then 'From200To299'
            When money < 1000 Then 'From300To999'
                              Else 'GE1000' End Bucket, 
       Count(*) Count
From Table
Group By Case When money < 100 Then 'LT100'
            When money < 200 Then 'From100To199'
            When money < 300 Then 'From200To299'
            When money < 1000 Then 'From300To999'
                              Else 'GE1000' End  

编辑:    如果存储桶的长度或大小是常量(或者可以表示为SQL表达式),则可以通过将存储桶定义为该表达式的输出来执行任意数量的存储桶,例如,如定义每100美元一桶:

Select Str(Floor(Cast(money / 100)), 8, 0)  Bucket, 
       Count(*) Count
From Table
Group By  Str(Floor(Cast(money / 100)), 8, 0)

或者,要获得高达1000美元的100美元桶,然后从那里获得1000美元的桶:

Select Case When Money < 1000 
            Then  Str(Floor(Cast(money / 100)), 8, 0) 
            Else Str(Floor(Cast(money / 1000)), 8, 0) End  Bucket, 
       Count(*) Count
From Table
Group By Case When Money < 1000 
            Then  Str(Floor(Cast(money / 100)), 8, 0) 
            Else Str(Floor(Cast(money / 1000)), 8, 0) End 

要获得累积计数,我将上述SQL查询的输出用作另一个SQL中的子查询:   以第一个为例:

  Select LT100,
         LT100 + From100To199 LT200,
         LT100 + From100To199 + From200To299  LT300,
         LT100 + From100To199 +  From200To299 + From300To999  LT1000,
         LT100 + From100To199 +  From200To299 + From300To999 + GE1000 Total     
  From ( Select Case When money < 100 Then 'LT100'
                When money < 200 Then 'From100To199'
                When money < 300 Then 'From200To299'
                When money < 1000 Then 'From300To999'
                                  Else 'GE1000' End Bucket, 
           Count(*) Count
         From Table
         Group By Case When money < 100 Then 'LT100'
                When money < 200 Then 'From100To199'
                When money < 300 Then 'From200To299'
                When money < 1000 Then 'From300To999'
                                  Else 'GE1000' End) Z

答案 1 :(得分:0)

SELECT
     SUM(CASE WHEN MONEY < 100 THEN 1 ELSE 0 END AS '0-100'
    ,SUM(CASE WHEN MONEY >= 100 AND MONEY < 200 THEN 1 ELSE 0 END AS '100-200'
    ,SUM(CASE WHEN MONEY >= 200 AND MONEY < 300 THEN 1 ELSE 0 END AS '200-300'
FROM
    Table

答案 2 :(得分:0)

有时在存储过程中使用循环最简单:

CREATE TABLE #tmp0(
bucket int,
accumulator int,
)

/* for(n = maxvalue; n > 0; n -= 100) */

Declare @n int
select @n = (select 100 + (100 * (max(moneyField) / 100)) from tbl)
while @n > 0
begin
    insert into #tmp0 (bucket, accumulator) 
        (select @n, count(*) from tbl where moneyField < @n)
    select @n = @n - 100
end
select * from #tmp0 order by bucket

drop table #tmp0