Question[SQL]:Can you create a cross-tab report in my SQL Server!

來源:互聯網
上載者:User

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

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.