在 SQl 服务器中旋转 table
Pivoting table in SQl Server
我们有 CurrencyRatestable 如下:
我们需要将这个 table 水平排列为:
TransactionCurrency|EUR rate|INR Rate|USD Rate|Effectie Date
GBP |0.893 |0.0115 |0.7992 |2019-06-18 00:00:00:000
INR |78.0005 |1 |69.7242 |2019-06-18 00:00:00:000
USD |1.1187 |0.0143 |1 |2019-06-18 00:00:00:000
EUR |1 |0.0128 |0.8939 |2019-06-18 00:00:00:000
GBP |0.8902 |0.0114 |0.7943 |2019-06-19 00:00:00:000
INR |78.0755 |1 |69.6667 |2019-06-19 00:00:00:000
USD |1.1207 |0.0144 |1 |2019-06-19 00:00:00:000
EUR |1 |0.0128 |0.8923 |2019-06-19 00:00:00:000
等等
我有 SQL 的基本知识。 PIVOT 函数可以做到这一点吗?查询的起点应该是什么?因为我试错了。
select * from (SELECT
[BaseCurrency] ,
[TransactionCurrency],
[EffectiveDate],
[Rate]
FROM [PDI].[dbo].[Dim_CurrencyRates]
)cur
PIVOT(
FOR [BaseCurrency] in ('EUR','INR','USD')
)As PivTab
不需要聚合的时候我经常用max
select
TransactionCurrency,
EUR as [EUR rate],
INR as [INR Rate],
USD as [USD Rate],
EffectiveDate
from [PDI].[dbo].[Dim_CurrencyRates]
pivot(
max(Rate)
for BaseCurrency in (EUR, INR, USD)) as pv
我们有 CurrencyRatestable 如下:
我们需要将这个 table 水平排列为:
TransactionCurrency|EUR rate|INR Rate|USD Rate|Effectie Date
GBP |0.893 |0.0115 |0.7992 |2019-06-18 00:00:00:000
INR |78.0005 |1 |69.7242 |2019-06-18 00:00:00:000
USD |1.1187 |0.0143 |1 |2019-06-18 00:00:00:000
EUR |1 |0.0128 |0.8939 |2019-06-18 00:00:00:000
GBP |0.8902 |0.0114 |0.7943 |2019-06-19 00:00:00:000
INR |78.0755 |1 |69.6667 |2019-06-19 00:00:00:000
USD |1.1207 |0.0144 |1 |2019-06-19 00:00:00:000
EUR |1 |0.0128 |0.8923 |2019-06-19 00:00:00:000
等等
我有 SQL 的基本知识。 PIVOT 函数可以做到这一点吗?查询的起点应该是什么?因为我试错了。
select * from (SELECT
[BaseCurrency] ,
[TransactionCurrency],
[EffectiveDate],
[Rate]
FROM [PDI].[dbo].[Dim_CurrencyRates]
)cur
PIVOT(
FOR [BaseCurrency] in ('EUR','INR','USD')
)As PivTab
不需要聚合的时候我经常用max
select
TransactionCurrency,
EUR as [EUR rate],
INR as [INR Rate],
USD as [USD Rate],
EffectiveDate
from [PDI].[dbo].[Dim_CurrencyRates]
pivot(
max(Rate)
for BaseCurrency in (EUR, INR, USD)) as pv