我有一个联合查询,它从两个不同的人群中获取计数。如何强制按查询中写入的顺序而不是按升序/降序返回结果?
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
我希望第一个结果始终作为第一行返回。这可能吗?
我有一个联合查询,它从两个不同的人群中获取计数。如何强制按查询中写入的顺序而不是按升序/降序返回结果?
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
我希望第一个结果始终作为第一行返回。这可能吗?
您必须使用 ORDER BY 子句指定顺序。在您的示例中,您可能会这样做:
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
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