天天看點

經典SQL之資料統計

有兩表:表v記錄各id進出的數量(進為正,出為負),表b記錄各id的餘數。

表v                                                    表b

id    rq                  進出數      ctc           id      rq                  餘數     ctc

1     2004-05-10    100          11            1      2004-05-10    100       11

1     2004-05-15    -20           11            1      2004-05-15    80        11

2     2004-05-10    200          11            2      2004-05-10    200       11

2     2004-05-12    50            11            2      2004-05-12    250       11 

2     2004-06-02    -100         11            2      2004-06-02    150       11

3     2004-05-12    50            13            3      2004-05-12     50        13

3     2004-05-20    -10           13            3      2004-05-20     40        13 

現在想統計某一時間段rq1至rq2内不同點ctc各天的進數、出數、餘數

比如要得到2004-05-10至2004-05-20之間每一ctc各天的變化結果,如下:

ctc       rq                  進                          出                             餘數

                   (進出數正值之和)  (進出數負值之和)    (id對應b表最大日期的餘數之和)

11    2004-05-10       300                          0                              300 

11    2004-05-12        50                           0                              350

11    2004-05-15         0                           20                             330

13    2004-05-12        50                           0                              50

13    2004-05-20         0                           10                             40

答案(csdn鄒建做答)

--查詢參數定義

declare @dt1 datetime,@dt2 datetime

select @dt1='2004-05-12',@dt2='2004-05-20'

--查詢語句

select ctc,rq=convert(char(10),rq,120)

 ,進=sum(case when 進出數>0 then 進出數 else 0 end)

 ,出=-sum(case when 進出數<0 then 進出數 else 0 end)

 ,餘數=(

  select sum(餘數)

  from b join(

   select id,rq=max(rq) from b

   where ctc=v1.ctc and rq <=v1.rq

    and exists(

     select 1 from v

     where ctc=v1.ctc and id=b.id

      and rq <=v1.rq)

   group by id

  )a on a.id=b.id and a.rq=b.rq)

from v v1

where rq between @dt1 and @dt2

group by ctc,rq

order by ctc,rq