Question: Can you createCross-TabReport 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
(
-- Total number and range of partition statistics
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
(
-- Rows to columns
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 ( ' 1994-01 1 ' As Datetime ) And
Dateadd (Mm, 3 , Cast ( ' 1994-01 1 ' 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 -- Derived table
Group By Stor_id -- Group by stor_id
)
Select * From Arg2
Note:
Sum(A. qty)Over(PartitionByT. stor_name) can be used for partition statistics, and the performance is optimized.
Pay attention to coalesce usage. Although it is not used here, It is very practical,
Coalesce (A. qty, 0) indicates (join). If a. qty returns NULL, 0 is passed by default.