Order of results with merge request

I have a join request that receives an invoice from two different groups. How to force the results to return in the order in which they are written in the query, and not in ascending / descending order?

select count(datediff(yyyy,dob,admitdate) as counts
from myTable
where condition
union
select count(datediff(yyyy,dob,admitdate) as counts
from myTable
where condition

I would like the first result to always return as the first row. Is it possible?

+3
source share
2 answers

You must specify the order with the ORDER BY clause. In your example, you can:

SELECT 1 AS seq, COUNT(datediff(yyyy,dob,admitdate) as counts
  FROM myTable
 WHERE ...condition-1...
UNION
SELECT 2 AS seq, COUNT(datediff(yyyy,dob,admitdate) as counts
  FROM myTable
 WHERE ...condition-2...
 ORDER BY seq
+5
source
select 1, count(datediff(yyyy,dob,admitdate) as counts
from myTable
where condition
union
select 2, count(datediff(yyyy,dob,admitdate) as counts
from myTable
where condition
order by 1
0
source

All Articles