2017-05-26 74 views
1

我有一個名爲產品表,SQL服務器 - 查詢一個奇怪的表

SELECT * FROM products; 

結果的結構,這是什麼使這個有趣的:

PRODUCT_1 | PRODUCT_2 | PRODUCT_3 | PRODUCT_4 | PRODUCT_ 5 
$ 10.00 | $ 20.00 | $ 25.00 | $ 30.00 | $ 35.00 

我知道我知道,地獄誰設計了這樣的桌子? 但不幸的是,這是我的。我需要做的是將此表從SQL Server通過C#應用程序複製到PostgreSQL。在PostgreSQL我對這個表的一個新的結構,但我不知道我怎樣才能使一個查詢能夠給我這樣的結構:

Product | Cost 
-------------------- 
Product_1 | $ 10.00 
Product_2 | $ 20.00 
Product_3 | $ 25.00 
Product_4 | $ 30.00 
Product_5 | $ 35.00 
+0

是僅限於5種產品嗎? – maSTAShuFu

回答

3

Select B.* 
From products A 
Cross Apply (
       values ('PRODUCT_1',[PRODUCT_1]) 
         ,('PRODUCT_2',[PRODUCT_2]) 
         ,('PRODUCT_3',[PRODUCT_3]) 
         ,('PRODUCT_4',[PRODUCT_4]) 
         ,('PRODUCT_5',[PRODUCT_5]) 
      ) B (Product,Cost) 

返回

Product  Cost 
PRODUCT_1 10.0000 
PRODUCT_2 20.0000 
PRODUCT_3 25.0000 
PRODUCT_4 30.0000 
PRODUCT_5 35.0000 

編輯 - 對於你不必指定F的動態方法ields和字段名

Select Product = C.Item 
     ,Cost = C.Value 
From products A 
Cross Apply (Select XMLData=convert(xml,(Select A.* for XML Raw))) B 
Cross Apply (
       Select Item = attr.value('local-name(.)','varchar(100)') 
         ,Value = attr.value('.','varchar(max)') 
       From B.XMLData.nodes('/row') as A(r) 
       Cross Apply A.r.nodes('./@*') AS B(attr) 
       Where attr.value('local-name(.)','varchar(100)') not in ('FieldsTo','Exclude') 
      ) C 
3

您可以按以下使用逆透視:

select * from Products 
unpivot(cost for Product in ([Product_1],[Product_2],[Product_3],[Product_4],[Product_5])) p 

對於動態腳本:

declare @cols varchar(max) 
declare @query nvarchar(max) 

select @cols = stuff((select ','+QuoteName(Column_Name) from INFORMATION_SCHEMA.COLUMNS where Table_name = 'Products' for xml path('')),1,1,'') 

Set @query = ' select Product, Cost from Products ' 
Set @query += ' unpivot(cost for Product in (' [email protected] + ')) p ' 

Select @query --Uncomment and execute below query if your created script is good 
--exec sp_executesql @query 
+0

加1 - 我不是積極unpivot在2008年可用。它已經很長一段時間。 –

+1

它是從2008年開始提供的......我是你的SQL查詢方法的忠實粉絲......你們永遠是獨一無二的......謝謝 –

+0

感謝你的笑容 –

2

試試這個簡單好用的感謝阿利薩Move Values from Rows to Columns in SQL Server 2008

select 'Product' as Product, PRODUCT_1 as Cost from products 
union all 
select 'Product_1 ', PRODUCT_1 from products 
union all 
select 'Product_2', Product_2 from products 
union all 
select 'Product_3 ', Product_3 from products 
union all 
select 'Product_4', Product_4 from products 
union all 
select 'Product_5 ', Product_5 from products 

結果:

Product | Cost 
-------------------- 
Product_1 | $ 10.00 
Product_2 | $ 20.00 
Product_3 | $ 25.00 
Product_4 | $ 30.00 
Product_5 | $ 35.00