2017-10-19 76 views
0

格式化我嘗試以下查詢:數據在MS SQL

SELECT Name,startdate,address from employee 

而且我得到了這樣的數據:

Name StartDate Address 
John 01/01/2017 na 

而我想這樣的數據:

Name  | John 
------------------------ 
StartDate | 01/01/2017 
Address | NA 

如何我可以編寫正確的查詢來獲得預期的結果嗎?

+0

考慮使用'UNPIVOT'。 –

+4

[Unpivot with column name]可能重複(https://stackoverflow.com/questions/19055902/unpivot-with-column-name) –

+0

@TimBiegeleisen unpivot? –

回答

3

The PIVOT & UNPIVOT運營商比他們的價值更痛苦。 Unpivoting列是使用交叉應用更容易,速度更快...

IF OBJECT_ID('tempdb..#TestData', 'U') IS NOT NULL 
DROP TABLE #TestData; 

CREATE TABLE #TestData (
    f_Name VARCHAR(10), 
    StartDate DATE, 
    Address VARCHAR(30) 
    ); 
INSERT #TestData(f_Name, StartDate, Address) 
VALUES ('Johm', '2017-01-01', 'n/a'); 

--================================================= 

SELECT 
    cav.ColLabel, 
    cav.ColValue 
FROM 
    #TestData td 
    CROSS APPLY (VALUES 
     (1, 'Name', td.f_Name), 
     (2, 'StartDate', CAST(td.StartDate AS VARCHAR(10))), 
     (3, 'Address', td.Address) 
     ) cav (SortVal, ColLabel, ColValue) 
ORDER BY 
    cav.SortVal; 

結果...

ColLabel ColValue 
--------- ------------------------------ 
Name  Johm 
StartDate 2017-01-01 
Address n/a