Sql 如何将多个记录作为单个记录获取
上面的结果集有三个值,第一行Sql 如何将多个记录作为单个记录获取,sql,sql-server,tsql,Sql,Sql Server,Tsql,上面的结果集有三个值,第一行timeone和timetwo中有值,而timethree、timefour、timefive和timesix中有空值,后面是其他四列 如何在一行中获取所有这些信息?您可以运行此查询: SELECT TOP(1) ID,NAME,AGE, (SELECT TOP(1) TIMEONE from [TABLE] WHERE ID = [ID] AND TIMEONE is not null) FROM [TABLE] 嵌套的select将获得第一个结果所需的时间部分
timeone
和timetwo
中有值,而timethree
、timefour
、timefive
和timesix
中有空值,后面是其他四列
如何在一行中获取所有这些信息?您可以运行此查询:
SELECT TOP(1) ID,NAME,AGE, (SELECT TOP(1) TIMEONE from [TABLE] WHERE ID = [ID] AND TIMEONE
is not null)
FROM [TABLE]
嵌套的select将获得第一个结果所需的时间部分,您可以再进行五次这样的查询,以获得其余时间。您可以运行此查询:
SELECT TOP(1) ID,NAME,AGE, (SELECT TOP(1) TIMEONE from [TABLE] WHERE ID = [ID] AND TIMEONE
is not null)
FROM [TABLE]
嵌套的select将获得第一个结果所需的时间部分,您可以再进行五次类似的查询,以获得其余时间。只需执行聚合:
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;
只需执行聚合:
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;
使用内部联接查询,如下所示:
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
查询稍微大一点。但我已经尝试用另一种方法来解决它,因为其中一个家伙已经给出了正确的答案。使用内部连接查询,如下所示:
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
查询稍微大一点。但我试图用另一种方式来解决这个问题,因为其中一个家伙已经给出了正确的答案。Pivot…………ISNUL(timeone,'01:00:03')。。。。依此类推,并使用select DISTINCTPivot……….ISNUL(timeone,'01:00:03')。。。。依此类推并使用selectDISTINCT@Shahul如果答案对你有帮助,你可以接受@如果答案对你有帮助,你可以接受。