sql 分类汇总统计代码

发布时间:2020-05-15编辑:脚本学堂
用sql语句进行分类汇总统计,有需要的朋友,可以参考下。

表结构如下:
id | DonTime | DonType | DonMoney |...

DonType 分为三种类型:社会个人捐款、单位捐款、单位个人捐款

要求:
按照每日,分类汇总三种类别的捐赠金额总和及捐赠次数。

sql语句如下所示:
 

复制代码 代码示例:
select convert ( char( 10 ),DonTime , 120) as DonDate , sum( DonMoney )as jz_all ,
sum (case dontype when ' 社会个人捐款 ' then DonMoney else 0 end) as jz_shgr,
count (case dontype when ' 社会个人捐款 ' then 1 else null end ) as jz_shgr_num,
sum (case dontype when ' 单位捐款' then DonMoney else 0 end ) as jz_dw ,
count (case dontype when ' 单位捐款' then DonMoney else null end) as jz_dw_num,
sum (case dontype when ' 单位个人捐款 ' then DonMoney else 0 end) as jz_dwgr,
count (case dontype when ' 单位个人捐款 ' then DonMoney else null end ) as jz_dwgr
from DonationInfo
where 1= 1
and datediff ( day, DonTime ,'2011-01-01' ) <= 0
and DATEDIFF ( day, DonTime ,'2011-02-04' ) >= 0
group by convert( char (10 ), DonTime, 120 )

请大家填充实际数据进行测试,以取得sql水平的快速提高,呵呵。