一道关于 SQLServer 交叉查询的 外企面试题

本文介绍如何使用SQL在MySQL Server中创建跨表报告,具体展示了如何获取1993年每个季度各商店的销售质量数据及总计。通过连接sales和stores表,并利用case when语句按季度汇总销售数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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
Bookbeat55 25 30 0 0
Doc-U-Mat: Quality Laundry and Books 85 0 85 0 0
Fricative Bookshop60 35 0 0 25
Total 25060 165025

答案:

select
b.stor_name,
total=sum(a.qty),
Q1=sum(case when datepart(mm,ord_date)<4 then a.qty else 0 end),
Q2=sum(case when datepart(mm,ord_date)>3 and datepart(mm,ord_date)<7 then a.qty else 0 end),
Q3=sum(case when datepart(mm,ord_date)>6 and datepart(mm,ord_date)<10 then a.qty else 0 end),
Q4=sum(case when datepart(mm,ord_date)>9 then a.qty else 0 end)
from sales as a
inner join stores as b on b.stor_id = a.stor_id
where a.ord_date BETWEEN convert(datetime,'1992-12-31 23:59:59') and convert(datetime,'1994-1-1')
group by b.stor_name
union
select 'total',
sum(a.qty),
sum(case when datepart(mm,ord_date)<4 then a.qty else 0 end),
sum(case when datepart(mm,ord_date)>3 and datepart(mm,ord_date)<7 then a.qty else 0 end),
sum(case when datepart(mm,ord_date)>6 and datepart(mm,ord_date)<10 then a.qty else 0 end),
sum(case when datepart(mm,ord_date)>9 then a.qty else 0 end)
from sales as a
inner join stores as b on b.stor_id = a.stor_id
where a.ord_date BETWEEN convert(datetime,'1992-12-31 23:59:59') and convert(datetime,'1994-1-1')

没有pubs数据库的可以到这里找到创建pubs数据库的sql脚本.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值