在SQL Server中转换数据

时间:2017-11-19 22:31:54

标签: sql-server transform

我今天收到了产品提供商的数据。

AdviserName|IF-Nov16|IF-Dec16|NB-Nov16|NB-Dec16|CN-Nov16|CN-Dec16|TotalPolcy|Provider|
-----------|--------|--------|--------|--------|--------|--------|----------|--------|
John Smith |$100    |$100    |$50     |$25.50  |-$20    |-$30    |12        |ANZ     |
Adrian Ken |$200    |$250    |$1000   |$2000   |-$500   |-$700   |30        |AXA     |

如何将上表转置到下方?

AdviserName|Month|Year|Status|Amount     |TotalPolicy|Provider|
-----------|-----|----|------|-----------|-----------|--------|
John Smith |Nov  |16  |IN    |$100       |12         |ANZ     |
John Smith |Dec  |16  |IN    |$100       |12         |ANZ     |
John Smith |Nov  |16  |NB    |$50        |12         |ANZ     |
John Smith |Dec  |16  |NB    |$25.50     |12         |ANZ     |
John Smith |Nov  |16  |CN    |-$20       |12         |ANZ     |
John Smith |Dec  |16  |CN    |-$30       |12         |ANZ     |
Adrian Ken |Nov  |16  |IN    |$200       |30         |AXA     |
Adrian Ken |Dec  |16  |IN    |$250       |30         |AXA     |
Adrian Ken |Nov  |16  |NB    |$1000      |30         |AXA     |
Adrian Ken |Dec  |16  |NB    |$2000      |30         |AXA     | 
Adrian Ken |Nov  |16  |CN    |-$500      |30         |AXA     |
Adrian Ken |Dec  |16  |CN    |-$700      |30         |AXA     |

到目前为止,我所做的是将数据从SQL下载到excel,逐个转置数据,然后将其放回SQL。然而,大约有4000行数据,我放弃了。

如何构建查询来转换这些数据?我正在使用SQL Server 2012。

感谢。

2 个答案:

答案 0 :(得分:2)

您可以尝试在T-SQL中使用cross apply功能,或者您可以使用我认为更简单的语法,它允许您通过values与{{1}进行几乎所见即所得的布局}。 NB 为每组新值形成一个新行:

SELECT t.AdviserName, ca.Month, ca.Year, ca.Status, ca.Amount, t.TotalPolicy, t.Provider
FROM YourTable t
CROSS APPLY (
        ('Nov', 16, 'IN', t.[IF-Nov16])
      , ('Dec', 16, 'IN', t.[IF-Dec16])
      , ('Nov', 16, 'NB', t.[NB-Nov16])
      , ('Dec', 16, 'NB', t.[NB-Dec16])
      , ('Nov', 16, 'CN', t.[CN-Nov16])
      , ('Dec', 16, 'CN', t.[CN-Dec16])
    ) ca (Month, Year, Status, Amount)

这个技巧在这里得到了很好的解释:Spotlight on UNPIVOT, Part 1(Brad Schultz)

答案 1 :(得分:2)

如果您愿意,以下是unpivot语法的示例。

create table dbo.dataTable
    (
        AdviserName varchar(100)
        , [IF-Nov16] smallmoney
        , [IF-Dec16] smallmoney
        , [NB-Nov16] smallmoney
        , [NB-Dec16] smallmoney
        , [CN-Nov16] smallmoney
        , [CN-Dec16] smallmoney
        , TotalPolcy int
        , [Provider] char(3)
    )

insert into dbo.dataTable
values ('John Smith', 100, 100, 50, 25.50, -20, -30, 12, 'ANZ')
    , ('Adrian Ken', 200, 250, 1000, 2000, -500, -700, 30, 'AXA')


select a.AdviserName
, substring(a.col_nm, 4, 3) as [Month]
, substring(a.col_nm, 7, 2) as [Year]
, substring(a.col_nm, 1, 2) as [Status]
, a.Amount
, a.TotalPolcy
, a.[Provider]
from dbo.dataTable as dt
unpivot (Amount for Col_Nm in ([IF-Nov16], [IF-Dec16], [NB-Nov16], [NB-Dec16], [CN-Nov16], [CN-Dec16])) as a