如何在sql中使用order by和union all? [英] How to use order by with union all in sql?

查看:54
本文介绍了如何在sql中使用order by和union all?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了下面给出的 sql 查询:

I tried the sql query given below:

SELECT * FROM (SELECT * 
FROM TABLE_A ORDER BY COLUMN_1)DUMMY_TABLE
UNION ALL 
SELECT * FROM TABLE_B 

它导致以下错误:

ORDER BY 子句在视图、内联函数、派生函数中无效表、子查询和公用表表达式,除非 TOP 或 FOR还指定了 XML.

The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP or FOR XML is also specified.

我需要在 union all 中使用 order by.我该如何实现?

I need to use order by in union all. How do I accomplish this?

推荐答案

SELECT  * 
FROM 
        (
            SELECT * FROM TABLE_A 
            UNION ALL 
            SELECT * FROM TABLE_B
        ) dum
-- ORDER BY .....

但是如果您想将 Table_A 中的所有记录放在结果列表的顶部,您可以添加用于排序的用户定义值,

but if you want to have all records from Table_A on the top of the result list, the you can add user define value which you can use for ordering,

SELECT  * 
FROM 
        (
            SELECT *, 1 sortby FROM TABLE_A 
            UNION ALL 
            SELECT *, 2 sortby FROM TABLE_B
        ) dum
ORDER   BY sortby 

这篇关于如何在sql中使用order by和union all?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆