我有一个包含以下列的联接表:
id_cat | category | risk_factor | rs | id_sample | R1 | R2 | rs
我希望生成一个像:
这样的表category | total | high | medium | low
其中,总数,高,中,低是从计算得出的总和,该计算确定风险因素是否为' risk_factor'等于' R1'和/或' R2'对于那一行,
根据以下伪代码
SELECT
category,
count(*) as total,
sum(case when R1 = risk_factor and R2 = risk_factor) = 1 as high,
sum(case when R1 = risk_factor or R2 = risk_factor) = 1 as med,
sum(case when R1 <> risk_factor and R2 <> risk_factor) = 1 as low
FROM mydatabase.mytable1
JOIN mydatabase.mytable2 as r
ON mytable1.rs=r.rs
WHERE id_sample = 'sample1'
GROUP BY category
ORDER BY category ASC;
我的问题是如何在sum语句中正确语法case语句。
答案 0 :(得分:2)
选择 类别,
COUNT(*) AS total,
SUM(CASE WHEN R1 = risk_factor AND R2 = risk_factor THEN 1 ELSE 0 END ) AS high,
SUM(CASE WHEN R1 = risk_factor OR R2 = risk_factor THEN 1 ELSE 0 END ) AS med,
SUM(CASE WHEN R1 <> risk_factor AND R2 <> risk_factor THEN 1 ELSE 0 END ) AS low
FROM mydatabase.mytable1
JOIN mydatabase.mytable2 AS r
ON mytable1.rs=r.rs
WHERE id_sample = 'sample1'
GROUP BY category
ORDER BY category ASC;