答案 0 :(得分: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!)
答案 1 :(得分: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