在组合来自单个表

时间:2016-06-17 06:21:55

标签: sql sql-server union

我想将单个表中的2个结果合并,但union all附近的语法不正确。

SELECT  
    ID as 'ABC','1' as 'PQR','2' as 'XYZ', Total as 'LMN'
FROM 
    Employee 
ORDER BY 
    ID

UNION ALL

SELECT  
    ID as 'ABC','1' as 'PQR','2' as 'XYZ', Total as 'LMN'
FROM 
    Employee 
ORDER BY 
    ID

但上面的查询失败并显示错误

  

union

附近的语法不正确

注意:我使用了union all,因为我不想删除重复的行。

2 个答案:

答案 0 :(得分:3)

您需要删除第一个ORDER BY子句:

SELECT
    ID AS 'ABC',
    '1' AS 'PQR',
    '2' AS 'XYZ',
    Total AS 'LMN'
FROM Employee
UNION ALL
SELECT
    ID AS 'ABC',
    '1' AS 'PQR',
    '2' AS 'XYZ',
    Total AS 'LMN'
FROM Employee
ORDER BY ID

UNION文档的示例F说:

  

SELECT语句中的任何UNION语句包含ORDER BY时   该子句应该放在所有SELECT语句之后。

答案 1 :(得分:2)

从联盟的第一部分删除订单