我想结合这两个SQL查询:
SELECT * FROM "Contracts" WHERE
"productType" = 'RINsell' AND
"clearTime" IS NULL AND
"holdTime" IS NOT NULL
ORDER BY "generationTime";
和
SELECT * FROM "Contracts" WHERE
"productType" = 'RINsell' AND
"clearTime" IS NULL AND
"holdTime" IS NULL
ORDER BY "contractLimitPrice";
当我运行每个语句时,我得到了我想要的结果,我只想顺序地得到两个结果。我的第一个想法是使用UNION ALL,因为这些选择将是不相交的,但我发现你不能在UNION
之后使用ORDER BY
。我搜索了很多,大多数人建议在ORDER BY
之后执行UNION
,但每个查询都有不同的ORDER BY
条件。
答案 0 :(得分:2)
如果您希望第一个查询的结果在第二个结果之前,您可以从where子句中删除holdtime
,并使用类似
order by
case when holdTime is not null then 0 else 1 end, --first query comes first
case when holdTime is not null --different orders for queries
then generationTime
else contractLimitPrice
end
答案 1 :(得分:0)
...但我发现您无法在
UNION
之后使用ORDER BY
。
嗯,你看起来不够努力:
(
SELECT *
FROM "Contracts"
WHERE "productType" = 'RINsell'
AND "clearTime" IS NULL
AND "holdTime" IS NOT NULL
ORDER BY "generationTime"
)
UNION ALL
)
SELECT *
FROM "Contracts"
WHERE "productType" = 'RINsell'
AND "clearTime" IS NULL
AND "holdTime" IS NULL
ORDER BY "contractLimitPrice"
)
请注意括号。 Per documentation:
(
ORDER BY
和LIMIT
可以附加到子表达式(如果是) 括在括号中。没有括号,这些条款将是 用于应用UNION
的结果,而不是右侧输入 表达。)
密切相关的答案:
Sum results of a few queries and then find top 5 in SQL
除此之外:我真的会get rid of those CaMeL case identifiers。使用Postgres中的全小写法律标识符,您的生活会轻松得多。