[英]How to get distinct count along with different conditions
我有 4 個不同的結果類別:正常、輕度、中度和重度
我想獲取每個類別的患者數量,如果是嚴重類別,我想根據其相應的結果值(例如,Severe_500_to_599、Severe_600_to_699、Severe_700_to_799 和severe_>800)進一步將其划分為更多類別,然后獲取計數這些子類別。
目前我正在通過提出具體條件來進行個人計數,
select count(distinct SOURCE_PATIENT_ID)
from Table1
where RESULT_CATEGORY = 'SEVERE' and RESULT_VALUE_STANDARDIZED between '1100' and '1199' and RESULT_UNIT <> 'MG/DL';
有沒有辦法在一個查詢中獲得所有結果?
謝謝!
您可以使用 Union all 來組合您的查詢
select 'SEVERE-599' as ResultCategory,
count(distinct SOURCE_PATIENT_ID)
from Table1
where RESULT_CATEGORY = 'SEVERE' and RESULT_VALUE_STANDARDIZED between '500' and '599' and RESULT_UNIT <> 'MG/DL'
Union ALL
select 'SEVERE-699' as ResultCategory,
count(distinct SOURCE_PATIENT_ID)
from Table1
where RESULT_CATEGORY = 'SEVERE' and RESULT_VALUE_STANDARDIZED between '600' and '699' and RESULT_UNIT <> 'MG/DL'
此處可以使用帶有QUALIFY
子句的 Window function 將數據集划分為單獨的桶,然后從這些桶中獲取單個值。
以下查詢 -
with data (patient_id, result_category, result_value) as (
select * from values
(110,'Normal',35),
(123,'Normal',135),
(111,'Mild',151),
(191,'Mild',199),
(112,'Moderate',211),
(113,'Severe',501),
(115,'Severe',500),
(144,'Severe',723),
(146,'Severe',801)
)
select
case
when result_category = 'Severe'
AND result_value between 500 and 599
then
'Severe Bucket (500-599)'
when result_category = 'Severe'
AND result_value between 700 and 799
then
'Severe Bucket (700-799)'
when result_category = 'Severe'
AND result_value between 800 and 899
then
'Severe Bucket (800-899)'
else
result_category
end new_result_category,
sum(result_value) over (partition by new_result_category) patient_count
from data
qualify row_number() over (partition by new_result_category
order by patient_id desc) = 1;
將給出如下結果 -
NEW_RESULT_CATEGORY | PATIENT_COUNT 個 |
---|---|
溫和的 | 350 |
緩和 | 211 |
嚴重鏟斗 (700-799) | 723 |
嚴重鏟斗 (500-599) | 1001 |
普通的 | 170 |
嚴重鏟斗 (800-899) | 801 |
我可以建議被低估的grouping sets
嗎?
with cte as
(select *, case when result_value between 500 and 599 then 'Severe Bucket (500-599)'
when result_value between 700 and 799 then 'Severe Bucket (700-799)'
when result_value between 800 and 899 then 'Severe Bucket (800-899)'
end as breakdown
from data)
select coalesce(result_category,breakdown) as category,
count(distinct patient_id) as patient_count
from cte
group by grouping sets (result_category,breakdown)
having coalesce(result_category,breakdown) is not null
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.