问题
I received a data from product providers today.
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 |
How do i transpose the table above to below?
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 |
So far what I have done is download the data from SQL to excel, transpose the data one by one, and put it back to SQL. However there are around 4000 rows of data and I'm giving up.
How to build query to transform these data? I'm using SQL server 2012.
Thanks.
回答1:
If you'd like, here is an example of what the unpivot syntax would look like.
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
回答2:
You could attempt to use the unpivot feature in T-SQL, or you could use what I believe is a simpler syntax which allows you an almost WYSIWYG layout through a cross apply with values. NB A new row is formed for each new set of values:
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)
This technique is well explained here: Spotlight on UNPIVOT, Part 1 (by Brad Schultz)
来源:https://stackoverflow.com/questions/47382716/transform-data-in-sql-server