我有一系列由union加入的查询。例如:
SELECT
SUM(WHOS) [CRITERIA]
FROM ONFIRST
UNION
SELECT
COUNT(WHATS) [CRITERIA]
FROM ONSECOND
UNION
SELECT
IDONTKNOW [CRITERIA]
FROM ONTHIRD
等
查询结果并不总是以相同的顺序返回,我希望结果与我编写查询的顺序相同。
示例:有时我首先获得WHOS的SUM,有时我首先获得COUNT的数量。
实现这一目标的最佳方式是什么?
答案 0 :(得分:1)
您可以使用虚拟订单列轻松控制此操作,并按该值排序:
;With Cte As
(
Select Sum(WHOS) CRITERIA
, 1 As Ord
From ONFIRST
Union
Select Count(WHATS) CRITERIA
, 2 As Ord
From ONSECOND
Union
Select IDONTKNOW CRITERIA
, 3 As Ord
From ONTHIRD
)
Select CRITERIA
From Cte
Order By Ord Asc;