SQL 逆透视列组

SQL Unpivot groups of columns

老实说,我什至不确定是否有更合适的函数来解决我的问题,因为除了基本 Select 之外,我对 SQL 2014 中的许多函数都不熟悉,更新、删除、插入...

我有这个table:

RegionID    Price1    Price1New    Efx1Date    Price2    Price2New    Efx2Date
   1         3.5        4.0        10/23/17     3.75       4.5        10/20/17
   2         3.25       4.5        10/21/17     4.25       4.0        10/21/17

我怎样才能得到结果?

RegionID    PriceList    Current    NewPrice    EfxDate
   1        Price1        3.5        4.0        10/23/17
   1        Price2        3.75       4.5        10/20/17
   2        Price1        3.25       4.5        10/21/17
   2        Price2        4.25       4.0        10/21/17

你可以使用 UNION ALL

SELECT RegionId, 'Price1' AS PriceList, Price1 AS [Current], Price1New AS NewPrice, Efx1Date AS EfxDate
UNION ALL
SELECT RegionId, 'Price2' AS PriceList, Price2 AS [Current], Price2New AS NewPrice, Efx2Date AS EfxDate

根据要求,使用 UNPIVOT 表示法,查询将如下所示

--create table T(RegionID int,   Price1  money,  Price1New   money, Efx1Date  date,  Price2  money,  Price2New money,  Efx2Date date)
--insert into T values 
--(1,3.5 ,4.0,'10/23/17', 3.75,  4.5, '10/20/17'),(2,3.25,4.5,'10/21/17', 4.25,  4.0, '10/21/17')

select 
RegionId,
priceList,
[Current],
NewPrice= Case 
            when priceList='Price1'
            then Price1New
            when priceList='Price2'
            then Price2New
          end,
EfxDate= Case 
            when priceList='Price1'
            then Efx1Date    
            when priceList='Price2'
            then Efx2Date    
          end
from
(select * from T)s
unpivot
(
    [Current] for [priceList] in ([Price1],[Price2])
    )up
 order by 1,2

See working demo