您可以通过row_number() over(partition by..
喜欢这样做,
select
AGE,
DIAGNOSIS_CODE_1,
total_count
from (
select
AGE,
DIAGNOSIS_CODE_1,
count(DIAGNOSIS_CODE_1) as total_count,
row_number() over (partition by AGE order by count(DIAGNOSIS_CODE_1) desc) rnk
from Health
where age in (7, 9)
group by AGE, DIAGNOSIS_CODE_1
) x
where rnk = 1
或者你可以使用union all
等;
with tmp_1 as (
select TOP 1 AGE, DIAGNOSIS_CODE_1, count(DIAGNOSIS_CODE_1) as total_count
from Health
where age = 7
group by AGE, DIAGNOSIS_CODE_1
order by total_count DESC
),
tmp_2 as (
select TOP 1 AGE, DIAGNOSIS_CODE_1, count(DIAGNOSIS_CODE_1) as total_count
from Health
where age = 9
group by AGE, DIAGNOSIS_CODE_1
order by total_count DESC
)
select AGE, DIAGNOSIS_CODE_1, total_count from tmp_1
union all
select AGE, DIAGNOSIS_CODE_1, total_count from tmp_2
'SELECT * FROM(SELECT TOP 1 AGE,DIAGNOSIS_CODE_1,从健康 计数(DIAGNOSIS_CODE_1)作为TOTAL_COUNT 其中年龄= 7 组由AGE,DIAGNOSIS_CODE_1 UNION ALL 选择TOP 1 AGE,DIAGNOSIS_CODE_1,计数(DIAGNOSIS_CODE_1)从健康 其中年龄= 9 组按年龄,DIAGNOSIS_CODE_1 )由x.total_count X为了desc'的 –
可能的复制[SQL服务器?:如何使用UNION两个查询,这两个有一个WHERE子句] TOTAL_COUNT ( http://stackoverflow.com/questions/5426767/sql-server-how-to-use-union-with-two-queries-that-both-have-a-where-clause) – venkat
@Sandeep - 请给予e一些示例数据与两个查询的预期输出。 – Utsav