SQL按月統計

2021-06-01 09:07:29 字數 1311 閱讀 6342

做統計就要和時間打交道。。。 

一:當前年的月統計

select b.number as [month], sum(a.a4012) shouru,sum(a.a4011) feiyong,sum(a.a4012-a4011) lirun

from a040a001 a

right join

(select number from master..spt_values where type='p' and number between 1 and 11) b

on b0110='00172' and a.a4035>'2011-1-1' and month(a.a4035)=b.number

group by b.number,year(a.a4035) order by [month]

結果:

二:時間段內按月統計

1.首先獲得日期表

with date as

( select convert(char(7),dateadd(month,number,'2011-07-01'),120) riqi

from

master..spt_values

where

type='p'

and

dateadd(month,number,'2011-07-01')<='2012-02-01'

)select* from date

2.操作

with date as

( select convert(char(7),dateadd(month,number,'2011-07-01'),120) riqi

from

master..spt_values

where

type='p'

and

dateadd(month,number,'2011-07-01')<='2012-02-01'

)select date.riqi , sum(a.a4012) shouru,sum(a.a4011) feiyong,sum(a.a4012-a4011) lirun

from a040a001 a

right join

date

on b0110='00172' and a.a4035>'2011-1-1' and convert(char(7),a.a4035,120)=date.riqi

group by date.riqi

關於SQL 按月統計記錄數量

曾經查詢一年中每月資料數量都要select count 0 from table1 迴圈n次。最近突然發現group by的妙用。所以。select datepart yyyy,time as year,datepart mm,time as month,count 0 as count from ...

按月份統計

id logtimes 12010 03 1213 04 412 2010 04 1313 04 443 2010 05 1813 04 444 2010 06 1813 04 445 2010 07 1813 04 446 2010 05 1813 04 447 2010 05 1813 04 4...

統計 Oracle按月統計(詳細)

建立表 test cteate table test id number not null,modifiedtime date not null 按月統計 select to char t.modifiedtime,yyyy mm time,count count from test t 這裡可加查...