SQL 按年,月,日統計相關函式

2022-06-07 04:45:07 字數 2335 閱讀 2627

說明:

統計每月下組織每天費用記錄

表:membermoney  

字段   id   主鍵

使用者id varchar(50)

onorgid 所在單位 varchar(50)

realpay 金額 decimal(18,2)

paydate 繳費時間 datetime

addyear 年 int

paymonth 月 int

select p.* ,o.shortname as onorgname from

(   

select a.*,isnull(b.onlinefee,0) onlinefee,isnull(c.cashfee,0) cashfee from

(   

select onorgid,cast( cast(year(paydate) as

varchar) +'-

'+cast(month(paydate) as

varchar) +'-

'+cast(day(paydate) as

varchar) as date) as pdate,sum(realpay) as pmoney from

membermoney

where addyear=

2020

and paymonth=

9and paydate is

notnull

and onorgid=

''group

by onorgid,year(paydate),month(paydate),day

(paydate) )a

left

join

( select onorgid,cast( cast(year(paydate) as

varchar) +'-

'+cast(month(paydate) as

varchar) +'-

'+cast(day(paydate) as

varchar) as date) as

pdate,

sum(realpay) as

onlinefee

from membermoney where addyear=

2020

and paymonth=

9and paydate is

notnull

and onorgid=

''and paytype=

0group

by onorgid,year(paydate),month(paydate),day

(paydate)

)b

on a.onorgid=b.onorgid and a.pdate=

b.pdate

left

join

( select onorgid,cast( cast(year(paydate) as

varchar) +'-

'+cast(month(paydate) as

varchar) +'-

'+cast(day(paydate) as

varchar) as date) as pdate,sum(realpay) as cashfee from

membermoney

where addyear=

2020

and paymonth=

9and paydate is

notnull

and onorgid=

''and paytype=

1group

by onorgid,year(paydate),month(paydate),day

(paydate)

)c

on a.onorgid=c.onorgid and a.pdate=

c.pdate

) p

left

join base_organize o on p.onorgid=o.organizeid order

bypdate

isnull 判斷是否為null ,為null賦值0
cast(字段 as varchar) 例 int 轉 string

year(paydate) 得到年

month(paydate)得到月
day(paydate)得到天

實現統計的年,月,日

時間外掛程式用的mydate97,我用yii框架寫的 最終實現的結果為 如果選擇時間間隔在 30 天之內,則展示這三十天中每天的資料,如果時間間隔 大於30天小於2年,則展示的是以月份為單位的資料,如果時間間隔大於兩年,展示的是以年份為單位的資料。以下為封裝的方法,之前用highchars做的統計 ...

MySQL支援按年月日查詢

在業務環境中,總是想要篩選出不同時間條件下的資料,例如我只想查詢當天資料,當月資料或者本年資料。於是就想通過mysql自帶的幾個時間函式進行簡單的實現。select from cars location where year create time year now and month create...

sql月度分組 SQL語句按年 月 日 季度分組

1.按年份分組 select to char exportdate,yyyy sum amount from table1 group by to char exportdate,yyyy 年份 數量 2009 68 2010 137 2008 103 2.按月份分組 select to char ...