日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 人文社科 > 生活经验 >内容正文

生活经验

一道SQL统计试题

發布時間:2023/11/27 生活经验 23 豆豆
生活随笔 收集整理的這篇文章主要介紹了 一道SQL统计试题 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

根據上圖A表和B表,按照年份和地區生成1至12個月的數據,結果如下:

方法一:

select YEAR,AreaName,
MAX(case Month when '1' then Money else 0 end) as [1月],
MAX(case Month when '2' then Money else 0 end) as [2月],
MAX(case Month when '3' then Money else 0 end) as [3月],
MAX(case Month when '4' then Money else 0 end) as [4月],
MAX(case Month when '5' then Money else 0 end) as [5月],
MAX(case Month when '6' then Money else 0 end) as [6月],
MAX(case Month when '7' then Money else 0 end) as [7月],
MAX(case Month when '8' then Money else 0 end) as [8月],
MAX(case Month when '9' then Money else 0 end) as [9月],
MAX(case Month when '10' then Money else 0 end) as [10月],
MAX(case Month when '11' then Money else 0 end) as [11月],
MAX(case Month when '12' then Money else 0 end) as [12月]
from 
(
select B.AreaName, 
SUM(Money) as Money,YEAR(CreateOn) Year,Month(CreateOn) Month
from A left join B on A.AreaId=B.AreaId
group by AreaName, YEAR(CreateOn),Month(CreateOn)
) A group by Year,AreaName
order by Year,AreaName

方法二:

select Year,AreaName,
ISNULL([1],0) as [1月],ISNULL([2],0) as [2月],ISNULL([3],0) as [3月],ISNULL([4],0) as [4月],
ISNULL([5],0) as [5月],ISNULL([6],0) as [6月],ISNULL([7],0) as [7月],ISNULL([8],0) as [8月],
ISNULL([9],0) as [9月],ISNULL([10],0) as [10月],ISNULL([11],0) as [11月],ISNULL([12],0) as [12月]
from 
(
select B.AreaName, 
SUM(Money) as Money,YEAR(CreateOn) Year,Month(CreateOn) Month
from A left join B on A.AreaId=B.AreaId
group by AreaName, YEAR(CreateOn),Month(CreateOn)
)
A 
pivot
(sum(money)for Month in([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12]) 
) as pvt
order by Year,AreaName

方法三:

--先創建表變量,并插入月份數據
declare @tb table(Month varchar(2)) 
insert @tb select 1 union all select 2 union all select 3 union all select 4 union all
select 5 union all select 6 union all select 7 union all select 8 union all
select 9 union all select 10 union all select 11 union all select 12declare @sql varchar(8000)
set @sql = 'select Year,AreaName '
select @sql = @sql + ' , max(case Month when ''' + convert(varchar(10),Month) + ''' then Money else 0 end) [' + convert(varchar(10),Month) + '月]'
from 
(select Month from @tb--select distinct Month(CreateOn) Month from A 
) as a
set @sql = @sql + '  from 
(select B.AreaName, SUM(Money) as Money,YEAR(CreateOn) Year,Month(CreateOn) Monthfrom A left join B on A.AreaId=B.AreaIdgroup by AreaName, YEAR(CreateOn),Month(CreateOn)
)
tb group by Year,AreaName'
--print @sql
exec(@sql) 

轉載于:https://www.cnblogs.com/gdjlc/archive/2011/07/16/2108179.html

總結

以上是生活随笔為你收集整理的一道SQL统计试题的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。