2010-01-16 88 views
0

說如果我有一個2列 - ID,金錢的表。 我想做一個查詢,以找出多少ID有錢少於100,200,300,...,10000 我應該如何在SQL Server中做到這一點?我需要使用變量嗎?在SQL Server中積累計數

回答

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 
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) 

,或者有100個美元水桶高達1000 $,然後$ 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 querys的輸出作爲另一個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 
+0

謝謝回答。如果範圍從0到1000000000?然後我必須輸入10,000,000次「當金錢<....」的聲明。有沒有更有效的方法來做到這一點? 順便說一句,這個問題是要求計算累計計數。所以這將是0-100計數,0-200計數,0-300等... – Stan 2010-01-17 17:36:46

+0

添加調整處理年問題...並做累計數現在.. – 2010-01-17 19:49:51

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