2015-10-07 65 views
0

我有這樣一個表,只有兩個功能對所有用戶在該表如何將行轉換爲列?

+-------+---------+-----------+----------+ 
| User | Feature | StartDate | EndDate | 
+-------+---------+-----------+----------+ 
| Peter | F1 | 2015/1/1 | 2015/2/1 | 
| Peter | F2 | 2015/3/1 | 2015/4/1 | 
| John | F1 | 2015/5/1 | 2015/6/1 | 
| John | F2 | 2015/7/1 | 2015/8/1 | 
+-------+---------+-----------+----------+ 

我想轉換成

+-------+--------------+------------+--------------+------------+ 
| User | F1_StartDate | F1_EndDate | F2_StartDate | F2_EndDate | 
+-------+--------------+------------+--------------+------------+ 
| Peter | 2015/1/1 | 2015/2/1 | 2015/3/1 | 2015/4/1 | 
| John | 2015/5/1 | 2015/6/1 | 2015/7/1 | 2015/8/1 | 
+-------+--------------+------------+--------------+------------+ 
+0

使用標記dbms產品,因爲您可能需要在此處提供產品特定的功能。 – jarlh

+0

它被稱爲轉位,往往是一個不好的做法。然而,這是一個通用的解決方案http://stackoverflow.com/questions/13372276/simple-way-to-transpose-columns-and-rows-in-sql。訣竅只是在同一張桌子上做出許多選擇並加入它 – pdem

+0

@pdem如何將數據呈現在數據透視中是一種不好的做法? –

回答

1

如果您正在使用SQL Server 2005或任何機會,PIVOT是您正在尋找。

+0

是的,首先我使用PIVOT將它轉換爲結果集,如[名稱],[F1],[F2],然後使用F1 F2作爲鍵加入原始表 – user1043963

0

最好的常規方式來執行這種操作是一個簡單的group by聲明。這應該在所有重大ODBMS工作:

select user, 
     max(case when feature='F1' then StartDate else null end) F1_StartDate, 
     max(case when feature='F1' then EndDate else null end) F1_EndDate, 
     max(case when feature='F2' then StartDate else null end) F2_StartDate, 
     max(case when feature='F2' then EndDate else null end) F2_EndDate 
    from table 
    group by user 

注:在評論中提到,這往往是不好的做法,因爲這取決於您的需求,它可以使數據更加努力的工作。但是,有些情況下,只有少量的數值纔有意義。

0

使用UNPIVOT & PIVOT這樣的:

測試數據:

DECLARE @t table 
    (User1 varchar(20),Feature char(2),StartDate date,EndDate date) 
INSERT @t values 
('Pete','F1','2015/1/1 ','2015/2/1'), 
('Pete','F2','2015/3/1 ','2015/4/1'), 
('John','F1','2015/5/1 ','2015/6/1'), 
('John','F2','2015/7/1 ','2015/8/1') 

查詢:

;WITH CTE AS 
(
    SELECT User1, date1, Feature + '_' + Seq cat 
    FROM @t as p 
    UNPIVOT  
    (date1 FOR Seq IN   
    ([StartDate], [EndDate])) AS unpvt 
) 
SELECT * FROM CTE 
PIVOT 
(MIN(date1) 
FOR cat 
IN ([F1_StartDate],[F1_EndDate],[F2_StartDate],[F2_EndDate]) 
) as p 

結果:

User1 F1_StartDate F1_EndDate F2_StartDate F2_EndDate 
John 2015-05-01 2015-06-01 2015-07-01 2015-08-01 
Pete 2015-01-01 2015-02-01 2015-03-01 2015-04-01 
0

這是位有一個黑客CTE

;WITH CTE AS (
SELECT [User], [Feature] + '_StartDate' AS [Type], StartDate AS [Date] 
FROM Table1 
UNION ALL 
SELECT [User], [Feature] + '_EndDate' AS [Type], EndDate AS [Date] 
FROM Table1) 
SELECT * FROM CTE 
PIVOT(MAX([Date]) FOR [Type] IN ([F1_StartDate],[F2_StartDate], [F1_EndDate], [F2_EndDate])) PIV 
+0

好消息。 –