在UNION ALL上选择最大记录

时间:2015-07-23 09:15:20

标签: sql sql-server tsql sql-server-2008-r2 union-all

我有以下内容正确地带回了3套结果

SELECT        TOP (1) rid,score, weight
FROM            dbo.tblThree
WHERE        (caseNo = '111111111')
ORDER BY rID DESC

SELECT        TOP (1) rid,score, weight
FROM            dbo.tblTwo
WHERE        (caseNo = '111111111')
ORDER BY rID DESC

SELECT        TOP (1) rid,score, weight
FROM            dbo.tblOne
WHERE        (caseNo = '111111111')
ORDER BY rID DESC

由于UNION ALL语句,在它们之间添加ORDER BY失败。但是,如果我摆脱它们,它会失败,因为它没有得到最新的记录。

这有更简单的解决方案吗?我想要的是一个输出3行的SQL语句。

4 个答案:

答案 0 :(得分:2)

尝试以下方法:

select * from ( select top (1) rid, score, weight
                from dbo.tblThree
                where caseNo = '111111111'
                order by rid desc) t1
union all
select * from ( select top (1) rid, score, weight
                from dbo.tblTwo
                where caseNo = '111111111'
                order by rid desc) t2
union all
select * from ( select top (1) rid, score, weight
                from dbo.tblOne
                where caseNo = '111111111' 
                order by rid desc) t3

答案 1 :(得分:2)

您可以使用以下内容获得所需的输出:

WITH data AS (
    SELECT        rid,score, weight, ROW_NUMBER() OVER (ORDER BY rID DESC) AS rn
    FROM            dbo.tblThree
    WHERE        (caseNo = '111111111')
    UNION ALL 
    SELECT        rid,score, weight, ROW_NUMBER() OVER (ORDER BY rID DESC) AS rn
    FROM            dbo.tblTwo
    WHERE        (caseNo = '111111111')
    UNION ALL
    SELECT        rid,score, weight, ROW_NUMBER() OVER (ORDER BY rID DESC) AS rn
    FROM            dbo.tblOne
    WHERE        (caseNo = '111111111')
)
SELECT *
FROM    data 
WHERE   rn = 1

答案 2 :(得分:0)

尝试此查询

select rID,score, weight from 
(SELECT        TOP (1) rID,score, weight,ROW_NUMBER() over(order by rID) as a
FROM            dbo.tblThree
WHERE        (caseNo = '111111111')
UNION ALL
SELECT        TOP (1) rid,score, weight,ROW_NUMBER() over(order by rID) as a
FROM            dbo.tblTwo
WHERE        (caseNo = '111111111')
UNION ALL
SELECT        TOP (1) rid,score, weight,ROW_NUMBER() over(order by rID) as a
FROM            dbo.tblOne
WHERE        (caseNo = '111111111'))t

答案 3 :(得分:0)

;WITH CTE1 as
(
  SELECT        TOP (1) rid,score, weight
  FROM            dbo.tblThree
  WHERE        (caseNo = '111111111')
  ORDER BY rID DESC
), CTE2 as
(
  SELECT        TOP (1) rid,score, weight
  FROM            dbo.tblTwo
  WHERE        (caseNo = '111111111')
  ORDER BY rID DESC
), CTE3 as
(
  SELECT        TOP (1) rid,score, weight
  FROM            dbo.tblOne
  WHERE        (caseNo = '111111111')
  ORDER BY rID DESC
)
SELECT
  rid,score, weight 
FROM CTE1
UNION ALL
SELECT
  rid,score, weight 
FROM CTE2
UNION ALL
SELECT
  rid,score, weight 
FROM CTE3