如何将多个记录作为单个记录获取

时间:2017-11-19 10:09:34

标签: sql sql-server tsql

enter image description here

以上结果集有三个值,第一行timetwotimethree包含值,而不是timefourtimefivetimesix和{{1}如果有其他四列,则为空值。

如何在一行中获取所有这些内容?

3 个答案:

答案 0 :(得分:5)

只需执行聚合:

SELECT ID,NAME,Age, 
       MAX(timeone) AS timeone,
       MAX(timetwo) AS timetwo,
       MAX(timethree) AS timethree,
       MAX(timefour) AS timefour,
       MAX(timefive) AS timefive,
       MAX(timesix) AS timesix
FROM [table]
GROUP  BY ID,NAME,Age;

答案 1 :(得分:0)

您可以运行此查询:

SELECT TOP(1) ID,NAME,AGE, (SELECT TOP(1) TIMEONE from [TABLE] WHERE ID = [ID] AND TIMEONE 
is not null)
FROM [TABLE]

嵌套选择将获得您想要的第一个结果的时间部分,您可以再进行五次这样的查询以获得剩余的时间。

答案 2 :(得分:0)

使用内部联接查询,如下所示:

SELECT t.Id, t.name, t.age, t.timeone, t.timetwo, t1.timethree, t1.timefour, t2.timefive, t2.timesix 
FROM 
    (SELECT Id, name, age, timeone, timetwo FROM [Table] WHERE timeone is not null and timetwo is not null) as t
INNER JOIN 
    (SELECT Id, timethree, timefour FROM [Table] WHERE timethree is not null and timefour is not null) as t1 
ON t.Id = t1.Id INNER JOIN 
    (SELECT Id, timefive, timesix FROM [Table] WHERE timefive is not null and timesix is not null) as t2 
ON t1.Id = t2.Id

查询有点大。但我试图以另一种方式解决它,因为其中一个人已经给出了正确答案。

相关问题