带有UNION和SQL的SQL ORDER BY

时间:2018-04-05 13:20:08

标签: sql sql-order-by union alias

我在Excel中使用SQL,我的查询有一个UNION语句,我需要按日期排序。

我有3个表:" Work_order_0"," Work_history_0"和" Note_0"。 " Work_0rder_0"和" Work_history_0"有相同的领域。

我的代码是:

SELECT  Work_order_0.WO_Key AS 'WO key',
        Work_order_0.Pos_key AS 'POS key',
        Work_order_0.Order_date AS 'Order date', 
        Work_order_0.Order_time/86400 AS 'Order time',
        Note_0.Note AS 'Note'   
FROM API3.PUB.Work_order Work_order_0 
LEFT JOIN API3.PUB.Note Note_0 ON Work_order_0.WO_Key=Note_0.Relate_key

UNION 

SELECT  Work_history_0.WO_Key AS 'WO key',  
        Work_history_0.Pos_key AS 'POS key',
        Work_history_0.Order_date AS 'Order date', 
        Work_history_0.Order_time/86400 AS 'Order time',
        Note_0.Note AS 'Note'
FROM API3.PUB.Work_history Work_history_0
LEFT JOIN API3.PUB.Note Note_0 ON Work_history_0.WO_Key=Note_0.Relate_key
ORDER BY 'Order date' DESC;

正如您在最后一行中所看到的,我尝试在ORDER BY子句中使用别名,但它给了我以下错误

  

按条款(7645)

排序的错误字段规范

有什么建议吗?提前谢谢。

3 个答案:

答案 0 :(得分:1)

您不能在同一查询中按顺序使用别名

SELECT * FROM
(SELECT  Work_order_0.WO_Key AS 'WO key',
        Work_order_0.Pos_key AS 'POS key',
        Work_order_0.Order_date AS 'Order date', 
        Work_order_0.Order_time/86400 AS 'Order time',
        Note_0.Note AS 'Note'   
FROM API3.PUB.Work_order Work_order_0 
LEFT JOIN API3.PUB.Note Note_0 ON Work_order_0.WO_Key=Note_0.Relate_key

UNION 

SELECT  Work_history_0.WO_Key AS 'WO key',  
        Work_history_0.Pos_key AS 'POS key',
        Work_history_0.Order_date AS 'Order date', 
        Work_history_0.Order_time/86400 AS 'Order time',
        Note_0.Note AS 'Note'
FROM API3.PUB.Work_history Work_history_0
LEFT JOIN API3.PUB.Note Note_0 ON Work_history_0.WO_Key=Note_0.Relate_key) AS T
ORDER BY 'Order date' DESC;

答案 1 :(得分:0)

不要对列别名使用单引号。他们只是造成问题。

其次,当您打算union时,请不要使用union all。表别名使查询更容易编写和读取。所以,我会推荐这样的东西:

SELECT w.*
FROM (SELECT wo.WO_Key, wo.Pos_key, wo.Order_date, wo.Order_time / 86400 AS Order_time,
             n.Note   
      FROM API3.PUB.Work_order wo LEFT JOIN
           API3.PUB.Note n
           ON wo.WO_Key = n.Relate_key
      UNION ALL  -- unless you really want to incur the overhead of removing duplicates
      SELECT  wh.WO_Key, wh.Pos_key, wh.Order_date, wh.Order_time / 86400,
              n.Note AS Note
      FROM API3.PUB.Work_history wh LEFT JOIN
           API3.PUB.Note n
           ON wh.WO_Key = n.Relate_key
     ) w
ORDER BY Order_date DESC;

并非所有数据库都需要ORDER BY的子查询。但是,没有人会将分隔的字符串识别为任何类型的表达式中的列名或键。

答案 2 :(得分:0)

对别名使用双引号,这对我有用。

Select count(*) as "Count of orders" from pub.Customer c Left Join Pub.Order o ON c."Cust-Num"=o."Cust-Num"
UNION
Select count(*) as "Count of orders" from pub.Customer c Left Join  Pub.Order o ON c."Cust-Num"<o."Cust-Num"
Order by "Count of orders";
     Count of orders
--------------------
                 220
                8160