首页 > 解决方案 > 无法正确获取 SQL 的预期联合输出

问题描述

问题:

没有正确订购,并且没有按预期布置代码/或使用约定。

问题:

Union此处需要使用运算符,为此,在使用的代码的第三行中指定了 find ,并且vendor_id数量少于最后一行代码中指定的数量。代码需要排序。

使用的代码:

SELECT job_id, po_id, 'Vendor ' || vendor_id as 'Reason'
FROM pos
WHERE vendor_id IS 'SOS'
UNION
SELECT job_id, po_id, 'Quantity < ' || quantity as 'Reason'
FROM pos
WHERE quantity < 10;

想要得到:

job_id      po_id       Reason
----------  ----------  ------------
002         AAA         Quantiy < 10
004         CCC         Quantiy < 10
004         CCC         Vendor SOS
005         EEE         Vendor SOS
006         GGG         Quantiy < 10

收到(来自 CodeRunner):

Runtime error
Program does not use the expected ORDER BY clause or is badly laid out.

有关更多详细信息,请参阅数据库架构(主键以粗体显示)。

使用了未知的 DBMS。表现得像PostgreSQL和不像mysql

标签: sqlgroup-byunioncoderunner

解决方案


job_id要按follow by排序po_id,只需ORDER BY在查询末尾添加子句。默认情况下排序顺序ASC(升序),DESC如果您想按降序排序,您可以添加。

SELECT
    job_id, 
    po_id, 
    'Vendor ' || vendor_id as 'Reason'
FROM pos
WHERE vendor_id = 'SOS'

UNION

SELECT 
    job_id,
    po_id, 
    'Quantity < ' || quantity as 'Reason'
FROM pos
WHERE quantity < 10

ORDER BY 
    job_id,
    po_id;

推荐阅读