在同一个表上组合两个SQL SELECT语句 [英] Combining two SQL SELECT statements on the same table
问题描述
我想合并这两个SQL查询:
I would like to combine these two SQL queries:
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,因为这个选择是不相交的,但我发现你不能在 ORDER BY >后使用
UNION
code>。我搜索了很多,大多数人建议在 UNION
之后执行 ORDER BY
,但每个查询有不同的 ORDER BY
条件。
When I run each statement, I get exactly the results I want, I would just like both results sequentially. My first thought was to use UNION ALL since this selections will be disjoint but I found that you can't use a UNION
after an ORDER BY
. I've searched quite a bit and most people suggest doing the ORDER BY
after the UNION
but each query has different ORDER BY
conditions.
推荐答案
如果您想要第一个查询在第二个结果之前,您可以从where子句中删除 holdtime
,并使用类似
If you want the results of the first query before the results of the second, you can remove holdtime
from the where clause, and use an order by like
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
这篇关于在同一个表上组合两个SQL SELECT语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!