一道IBM笔试题 按季度统计

本文介绍如何使用SQL在MySQL Server中创建跨表报表,具体展示了如何获取1993年每个商店每季度的销售质量及各季度总销售质量的数据。通过内连接结合使用DATEPART函数按季度汇总数据。

Can you create a cross-tab report in my SQL Server!
How can I get the report about sale quality for each store and each quarter and the total sale quality for each quarter at year 1993?
You can use the table sales and stores in datatabase pubs.
Table Sales record all sale detail item for each store. Column store_id is the id of each store, ord_date is the order date of each sale item, and column qty is the sale qulity. Table stores record all store information.
I want to get the result look like as below:
Output:
stor_name                                                               Total       Qtr1        Qtr2        Qtr3        Qtr4       
----------------------------------------------------------- ----------- ----------- ----------- ----------- -----------
Barnum's                                                                    50          0             50             0            0
Bookbeat                                                                    55          25          30          0           0
Doc-U-Mat: Quality Laundry and Books                85          0           85          0           0
Fricative Bookshop                                                     60          35          0           0           25
Total                                                                            250         60          165         0           25 

declare @sql varchar(4000)
set @sql = 'select stor_name ' 
select @sql = @sql + ', Qtr ' + datepart(quarter,ord_date) + ' = sum(case when datepart(quarter,ord_date) = '+datepart(quarter,ord_date)+' then qty else 0 end)'
from sales inner join stores on sales.stor_id = stores.stor_id
where year(ord_date) = 1993
group by datepart(quarter,ord_date)
set @sql = @sql + ' from sales inner join stores on sales.stor_id = stores.stor_id
where year(ord_date) = 1993
group by stor_name
'
print @sql 
exec(@sql)

知识点:

1.按季度统计

select datepart(quarter,ord_date)
from sales inner join stores on sales.stor_id = stores.stor_id
where year(ord_date) = 1993
group by datepart(quarter,ord_date)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值