SQL Unpivot列组

时间:2017-10-11 18:02:12

标签: sql sql-server tsql sql-server-2014 unpivot

老实说,我甚至不确定是否有更合适的功能来解决我的问题,因为我不熟悉SQL 2014中的许多功能,除了基本的选择,更新,删除,插入......

我有这张桌子:

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

2 个答案:

答案 0 :(得分:1)

根据要求,使用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

答案 1 :(得分:0)

您可以使用UNION ALL

console.log(JSON.stringify(k.data[0]["Account.FirstName"]));