将行转换为视图中的列

时间:2018-04-10 20:05:37

标签: sql-server

我有以下表格:DatesTransactions

日期

ID | Date      | DayOfQuarter
--------------------------------
1  | 1/1/2018  | 1
--------------------------------
2  | 1/2/2018  | 2

交易

ID | DateID | Type | Amount
-----------------------------
1  | 1      | 1    | 123.25
-----------------------------
2  | 1      | 2    | 456.58
-----------------------------
3  | 2      | 1    | 789.85
-----------------------------
4  | 2      | 2    | 987.96
-----------------------------

我想将Type列转换为单独的列,以使视图看起来像

Date     | DayOfQuarter  |  Type1  |  Type2
----------------------------------------------
1/1/2018 |  1            |  123.25  | 456.58
----------------------------------------------
1/2/2018 |  2            |  789.85  | 987.96

有办法做到这一点吗?到目前为止我已经尝试过了,但不确定是否有办法转置Type列

SELECT ddate.*, <Not sure at all>
FROM Transactions tran
LEFT JOIN Dates ddate ON tran.DateID = ddate.ID

目前,这将是一组静态的转置列

2 个答案:

答案 0 :(得分:1)

既然你声明它可以是静态的......你可以使用CASE

select
   [Date]
    ,DayOfQuarter = DateID
    ,Type1 = Sum(case when Type = 1 then Amount else 0 end)
    ,Type2 = Sum(case when Type = 2 then Amount else 0 end)
from Transactions tran
LEFT JOIN Dates ddate ON tran.DateID = ddate.ID
group by [Date], DateID

答案 1 :(得分:0)

使用PIVOT语法,您可以执行以下操作:

See live demo

select 
    [Date],
    [Dayofquarter],
    [type1]=MAX([1]),
    [type2]=MAX([2]) 
from 
(
    select 
        d.[Date],
        d.[Dayofquarter],
        t.*
    from dates d
    join transactions t
    on d.id=t.dateid
)src
pivot
(
    max(amount) for type in ([1],[2])
 )p
group by [Date],[Dayofquarter]