[英]SQL Server UNION change the order of query in results
我試圖在 SQL 服務器中合並 2 個查詢。 我希望第二個查詢行留在結果的最后,但它首先返回。
詢問:
SELECT
name,
total
FROM persons
UNION
SELECT
'TOTAL' as name
SUM(total) as total,
from persons
得到的結果:
name total
TOTAL 200
John 100
Matt 100
我想要的結果:
name total
John 100
Matt 100
TOTAL 200
我怎么能這樣做?
如果您想要特定訂單上的行,則需要使用ORDER BY
。
在沒有ORDER BY
子句的情況下,關系數據庫將以任何未指定的順序提供行; 這些行可能會按照您今天想要的順序顯示,但明天可能會改變。
例如,您可以這樣做:
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
解決了我用 union all 而不是 union
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.