【问题标题】:SQL Unpivot groups of columnsSQL Unpivot 列组
【发布时间】:2018-03-23 12:21:39
【问题描述】:

老实说,我什至不确定是否有更合适的函数来解决我的问题,因为除了基本的 Select、Update、Delete、Insert 之外,我不熟悉 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

【问题讨论】:

  • 嗯,你有所谓的重复组,它违反了 1NF。这就是你在这里挣扎的原因。您可以使用 UNPIVOT 来执行此操作。或者您也可以为此使用 UNION ALL。

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


【解决方案1】:

你可以使用 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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多