1

SQL Server 2008R2 には、次の 2 つのソース テーブルと 1 つの宛先テーブルがあります。ソースから宛先に到達するために TSQL でピボットを実行するにはどうすればよいですか? 緊急に必要です。

ソース表 1: ProdType


key     name
--------------
1       Magazines
2       Journals
3       Books
4       Newspaper

ソース表 2: 注文


seqno   ODate       Key     Qty      UnitPrice
--------------------------------------------------
1   2013-10-12      1    10       5
2   2013-10-12      4    20       3
3   2013-10-13      2    5        3
4   2013-10-14      4    50       5
5   2013-10-15      1    100      2.5

宛先テーブル: 注文の詳細

                         
Odate       Magazine       Journals       Books       Newspaper
-----------------------------------------------------------------   
12/10/2013      10    5    0    0       0      0      20      3
13/10/2013       0    0    5    3       0      0       0      0
14/10/2013       0    0    0    0       0      0      50      5
15/10/2013     100    2.5  0    0       0      0       0      0
-----------------------------------------------------------------
NOTE            *qty    *unit price                 

どんな助けでも大歓迎です!おわかりのように、私は T-SQL (または一般的な SQL) と SQL Server にまったく慣れていません。前もって感謝します!

4

2 に答える 2

1
with cte as (
    select
        O.ODate, P.Name,
        sum(O.Qty) as Qty,
        sum(O.UnitPrice * O.Qty) / sum(O.Qty) as UnitPrice
    from Orders as O
        inner join ProdType as P on P.Id = O.Id
    group by O.ODate, P.Name
)
select
    ODate,
    max(case when Name = 'Magazines' then Qty else 0 end) as Magazines_Qty,
    max(case when Name = 'Magazines' then UnitPrice else 0 end) as Magazines_UnitPrice,
    max(case when Name = 'Journals' then Qty else 0 end) as Journals_Qty,
    max(case when Name = 'Journals' then UnitPrice else 0 end) as Journals_UnitPrice,
    max(case when Name = 'Books' then Qty else 0 end) as Books_Qty,
    max(case when Name = 'Books' then UnitPrice else 0 end) as Books_UnitPrice,
    max(case when Name = 'Newspaper' then Qty else 0 end) as Newspaper_Qty,
    max(case when Name = 'Newspaper' then UnitPrice else 0 end) as Newspaper_UnitPrice
from cte
group by ODate

または、必要に応じて動的に:

declare @stmt nvarchar(max)

select @stmt =
      isnull(@stmt + ', ', '') +
      'max(case when Name = ''' + name + ''' then Qty else 0 end) as ' + quotename(name + '_Qty') + ',' +
      'max(case when Name = ''' + name + ''' then UnitPrice else 0 end) as ' + quotename(name + '_UnitPrice')
from ProdType

select @stmt = '
    with cte as (
        select
            O.ODate, P.Name,
            sum(O.Qty) as Qty,
            sum(O.UnitPrice * O.Qty) / sum(O.Qty) as UnitPrice
        from Orders as O
            inner join ProdType as P on P.Id = O.Id
        group by O.ODate, P.Name
    )
    select
        ODate, ' + @stmt + ' from cte group by ODate'

exec dbo.sp_executesql
    @stmt = @stmt

sql fiddle demo

于 2013-10-17T06:52:55.250 に答える