简体   繁体   English

SQL 服务器 UNION 更改结果中查询的顺序

[英]SQL Server UNION change the order of query in results

I triying to make a union of 2 queries in SQL Server.我试图在 SQL 服务器中合并 2 个查询。 I want that the second querie row stay at the final of the results, but it returns in a first place.我希望第二个查询行留在结果的最后,但它首先返回。

Query:询问:

SELECT 
name,
total
FROM persons

UNION

SELECT 
'TOTAL' as name
SUM(total) as total,
from persons

The result that a get:得到的结果:

name    total
TOTAL   200
John    100
Matt    100

The result that I want:我想要的结果:

name    total
John    100
Matt    100
TOTAL   200

How I can do that?我怎么能这样做?

If you want the rows on a specific order you need to use ORDER BY .如果您想要特定订单上的行,则需要使用ORDER BY

In the absence of an ORDER BY clause a relational database will provide the rows in any unspecified order;在没有ORDER BY子句的情况下,关系数据库将以任何未指定的顺序提供行; the rows may show up in the order you want today, but that may change tomorrow.这些行可能会按照您今天想要的顺序显示,但明天可能会改变。

For example, you can do:例如,您可以这样做:

select name, total
from (
  SELECT name, total, 1 as display_order
  FROM persons
 UNION ALL
  SELECT 'TOTAL', SUM(total), 2
  FROM persons
) x
ORDER BY display_order

SOLVED I used union all instead union解决了我用 union all 而不是 union

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM