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