使用UNION时如何显式排序查询结果?

时间:2017-09-20 15:53:46

标签: sql sql-order-by union

我正在尝试按以下顺序排序我的查询结果,我收到此错误消息。

如果语句包含UNION,INTERSECT或EXCEPT运算符,则ORDER BY项必须出现在选择列表中

SELECT [Category]
FROM [dbo].[Category]
WHERE LOWER([Category]) LIKE '%yearling%' OR LOWER([Category]) LIKE '%foal%' OR LOWER([Category]) LIKE '%in%utero%'
    UNION
SELECT [AcquisitionType] AS 'Category'
FROM [dbo].[AcquisitionType]
WHERE LOWER([AcquisitionType]) LIKE '%homebred%'
ORDER BY CASE WHEN [Category] = 'In Utero' THEN 1
              WHEN [Category] = 'In Utero & FS' THEN 2
              WHEN [Category] = 'FS in Utero' THEN 3
              WHEN [Category] = 'Foal' THEN 4
              WHEN [Category] = 'Foal & FS' THEN 5
              WHEN [Category] = 'FS Foal' THEN 6
              WHEN [Category] = 'Yearling' THEN 7
              WHEN [Category] = 'Yearling & FS' THEN 8
              WHEN [Category] = 'FS Yearling' THEN 9
              WHEN [Category] = 'N/a' THEN 10
              ELSE [Category] END ASC

我希望结果按照查询中列出的顺序返回。

我该怎么做?

我对此感到有些失落,所以感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

使用子查询或CTE:

STEPS operator++(STEPS& s, int) { auto res = s; ++s; return res; }

请注意,我已将int替换为SELECT Category FROM (SELECT [Category] FROM [dbo].[Category] WHERE LOWER([Category]) LIKE '%yearling%' OR LOWER([Category]) LIKE '%foal%' OR LOWER([Category]) LIKE '%in%utero%' UNION ALL SELECT [AcquisitionType] AS Category FROM [dbo].[AcquisitionType] WHERE LOWER([AcquisitionType]) LIKE '%homebred%' ) c ORDER BY . . .; UNION导致删除重复项的开销。

根据逻辑,您的两个子查询之间不能有重复。因此,除非每个子查询可能都有重复项,否则无需删除重复项。如果是,我建议UNION ALL而不是UNION查询。