您可以通過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