无法正确获得SQL的预期Union输出

时间:2018-05-06 02:50:37

标签: sql group-by union coderunner

故障:

没有正确排序,没有按预期布置代码/或使用约定。

问题:

此处需要使用Union运算符,并且为此找到所使用代码的第3行中指定的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.

See database schema for more details (Primary Keys are in bold).

使用了未知的DBMS。行为类似于PostgreSQL而非mysql

1 个答案:

答案 0 :(得分:1)

要按job_id排序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;