Question: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
Answer:
use [pubs]
go
with arg1 as
(
--分區統計總數及範圍限定
select t.stor_name, a.stor_id, a.ord_date, a.qty, SUM(a.qty) over(partition by t.stor_name) as totalqty
from [sales] a
inner join [stores] t
on t.stor_id = a.stor_id
where a.ord_date between CAST('1993-01-01' as datetime) and cast('1994-01-01' as datetime)
),
arg2 as
(
--行轉列Pivot
select MAX(stor_name) as stor_name, MAX(totalqty) as totalqty,
SUM(case when ord_date between CAST('1993-01-01' as datetime) and
DATEADD(mm, 3, CAST('1993-01-01' as datetime)) then qty else 0 end) as [Qtr1],
SUM(case when ord_date between CAST('1993-04-01' as datetime) and
DATEADD(mm, 3, CAST('1993-04-01' as datetime)) then qty else 0 end) as [Qtr2],
SUM(case when ord_date between CAST('1993-07-01' as datetime) and
DATEADD(mm, 3, CAST('1993-07-01' as datetime)) then qty else 0 end) as [Qtr3],
SUM(case when ord_date between CAST('1993-10-01' as datetime) and
DATEADD(mm, 3, CAST('1993-10-01' as datetime)) then qty else 0 end) as [Qtr4]
from ( select stor_name, stor_id, ord_date, qty, totalqty
from arg1) as D --派生表
group by stor_id --以stor_id分組
)
select * from arg2
注意:
SUM(a.qty) over(partition by t.stor_name) 可以進行分區統計,並且效能進行了最佳化。
另外注意coalesce的用法,雖然這裡沒有用到,但是十分實用,
coalesce(a.qty, 0) 表示(接合),如果a.qty返回null時,則使用預設傳0