我有以下表格:Dates
和Transactions
日期
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
现在,这将是一组静态的转置列
既然你说它可以是静态的...你可以使用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
使用PIVOT语法,您可以执行以下操作:
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]