将具有相同列的两个查询的结果组合到单个结果集中

时间:2013-10-23 20:33:53

标签: tsql sql-server-2008-r2

我可以使用一些大师帮助在一次通话中返回这些数据....

SELECT TOP 10 tblData.*, (
    SELECT  TOP 10 tblData.*
    FROM    tblData
    WHERE   pk >= 5481 AND dev_ID = 'REC1' AND code_ID = 'FMU' AND
                        CAST(event_date_time as DATE) = '10/18/2013'
    ORDER BY pk ASC
    )
FROM    tblData
WHERE   pk <= 5481 AND dev_ID = 'REC1' AND code_ID = 'FMU' AND 
        CAST(event_date_time as DATE) = '10/18/2013'
ORDER BY pk DESC

2 个答案:

答案 0 :(得分:1)

您应该尝试使用UNION或UNION ALL

UNION,指定要组合多个结果集并将其作为单个结果集返回。

ALL,将所有行合并到结果中。这包括重复。如果未指定,则删除重复的行。

(SELECT TOP 10 tblData.*
FROM    tblData
WHERE   pk <= 5481 AND dev_ID = 'REC1' AND code_ID = 'FMU' AND 
        CAST(event_date_time as DATE) = '10/18/2013'
ORDER BY pk DESC)
UNION 
(SELECT  TOP 10 tblData.*
FROM    tblData
WHERE   pk >= 5481 AND dev_ID = 'REC1' AND code_ID = 'FMU' AND
        CAST(event_date_time as DATE) = '10/18/2013'
ORDER BY pk ASC)

答案 1 :(得分:0)

我终于制作了一个有效的解决方案,在这里张贴给其他可能会遇到这个问题的人......

Select * From
(SELECT TOP 10 tblData.*
FROM    tblData
WHERE   pk <= 5481 AND dev_ID = 'REC1' AND code_ID = 'FMU' AND
    CAST(event_date_time as DATE) = '10/18/2013'
UNION
SELECT  TOP 10 tblData.*
FROM    tblData
WHERE   pk >= 5481 AND dev_ID = 'REC1' AND code_ID = 'FMU' AND
    CAST(event_date_time as DATE) = '10/18/2013') A
ORDER BY pk ASC