带有 UNION 子句的 ORDER BY

ORDER BY with UNION clause

我到处搜索,发现像下面的代码这样的东西应该可以工作。

SELECT id, name, age FROM A
UNION
SELECT id, name, age FROM B
ORDER BY name

我的查询是在特定日期之间搜索数据库中的每个值,然后只选择指定日期之前的几个值。此查询本身有效,但我想按某列对其进行排序,但出现错误:

ORDER BY items must appear in the select list if the statement contains a UNION, INTERSECT or EXCEPT operator

这是我的代码:

DECLARE @inidate DATE = '20201001', @findate DATE = '20201031'

SELECT bo.id, bo.date, bo.status
FROM BO (nolock)
JOIN BO2 (nolock) ON BO2.bo2stamp = BO.bostamp
WHERE (BO.date BETWEEN @inidate AND @findate)
  AND (BO.tabela1 IN ('INSTALED','CANCELED'))

UNION

SELECT bo.id, bo.date, bo.status
FROM BO (nolock)
JOIN BO2 (nolock) ON BO2.bo2stamp = BO.bostamp
WHERE (BO.date < @inidate)
  AND (BO.tabela1 NOT IN ('INSTALED','CANCELED'))
ORDER BY bo2.u_registration_date

我已经尝试了此处显示的代码,但在 ORDER BY

上出现错误

Expected AS, ID, or QUOTED_ID

SELECT * 
FROM
    ([my query])
ORDER BY bo2.u_registration_date

我也试过了

SELECT * 
FROM ([1st query])
UNION 
SELECT * 
FROM ([2nd query])
ORDER BY bo2.u_registration_date

您需要将 union 放在子查询中,并在外部查询中排序。此外,子查询需要 return 您要用于排序的列。

SELECT *
FROM (
    SELECT bo.id, bo.date, bo.status, bo2.u_registration_date
        FROM BO
        JOIN BO2 ON BO2.bo2stamp = BO.bostamp
        WHERE BO.date BETWEEN @inidate AND @findate AND BO.tabela1 IN ('INSTALED','CANCELED')
    UNION
        SELECT bo.id, bo.date, bo.status, bo2.u_registration_date
        FROM BO
        JOIN BO2 ON BO2.bo2stamp = BO.bostamp
        WHERE BO.date < @inidate AND BO.tabela1 NOT IN ('INSTALED','CANCELED')
) t
ORDER BY u_registration_date

请注意,此处使用 UNION 意义不大。这两个成员仅在日期过滤器上有所不同,因此从功能上讲,您的查询等同于:

SELECT bo.id, bo.date, bo.status, bo2.u_registration_date
FROM BO
JOIN BO2 ON BO2.bo2stamp = BO.bostamp
WHERE BO.date < @findate AND BO.tabela1 NOT IN ('INSTALED','CANCELED')
ORDER BY bo2.u_registration_date