2016-08-02 62 views
-4

當我執行查詢:SQL - 變換的列值

select Number, 
     Name, 
     [Date and Time], 
     Value 
from Source; 

我得到以下結果:

enter image description here

但我想這樣的結果:

enter image description here

這是可能的SQL?

+1

哪裏是你的查詢和數據庫管理系統? – Ash

+0

代碼在哪裏? –

+0

我添加的代碼,我使用sql – pape

回答

1

使用COALESCE(MAX(CASE您可以獲得預期的結果。

樣品執行與給定的樣本數據:

DECLARE @Source TABLE (Number INT, Name VARCHAR (100), DateAndTime VARCHAR (20), Value INT); 

INSERT INTO @Source(Number, Name, DateAndTime, Value) VALUES 
(1, 'Tom', '1.5.2016 11:29', 1), 
(1, 'Tom', '2.5.2016 10:45', 2), 
(2, 'Angelina', '7.5.2016 11:36', 1), 
(3, 'Fibi', '1.5.2016 11:34', 2), 
(3, 'Fibi', '1.5.2016 11:56', 3); 

SELECT Number, Name, 
     COALESCE(MAX(CASE WHEN Value = 1 THEN DateAndTime END), '') AS [1], 
     COALESCE(MAX(CASE WHEN Value = 2 THEN DateAndTime END), '') AS [2], 
     COALESCE(MAX(CASE WHEN Value = 3 THEN DateAndTime END), '') AS [3] 
FROM @Source 
GROUP BY Number, Name 
ORDER BY Number 

結果:

Number Name  1    2    3 
------------------------------------------------------------------ 
1  Tom   1.5.2016 11:29 2.5.2016 10:45 
2  Angelina 7.5.2016 11:36  
3  Fibi      1.5.2016 11:34 1.5.2016 11:56 
+0

非常感謝,就是這樣 – pape

1

您可以使用case表達式在不同列返回日期/時間值:

select Number, Name, 
     max(case when Value = 1 then [Date and Time] end) as [1], 
     max(case when Value = 2 then [Date and Time] end) as [2], 
     max(case when Value = 3 then [Date and Time] end) as [3] 
from Source 
group by Number, Name 

GROUP BY有沒有在一個單行返回名稱的所有值。 (注意:每個姓名只會返回一個值1,2,3!)

+0

我得到了兩行湯姆,第一次爲值1,第二次爲值2 ...我想所有在一行... – pape

+0

對不起,錯過了那個細節。將編輯。 – jarlh