我有以下查询:
SELECT M.TYPE, COUNT(F.CD) AS TOTAL,
COUNT(CASE WHEN F.GENDER=0 THEN F.GENDER END) AS NUM_MALE,
COUNT(CASE WHEN F.GENDER=1 THEN F.GENDER END) AS NUM_FEMALE
FROM MARC M
LEFT JOIN FUNCION F ON M.CD_FUNCION = F.CD
GROUP BY 1
即使FUNCION在表MARC中有多行,此查询也会按TYPE返回所有计数。但如果我只想要 DISTINCT FUNCIONS我该怎么办呢?第一次计算很简单,但我如何使用DISTINCT分隔男性和女性?
提前致谢!
答案 0 :(得分:1)
您可以将COUNT DISTINCT
与条件聚合一起使用:
SELECT M.TYPE, COUNT(DISTINCT F.CD) AS TOTAL,
COUNT(DISTINCT CASE WHEN F.GENDER = 0 THEN F.CD END) AS NUM_MALE,
COUNT(DISTINCT CASE WHEN F.GENDER = 1 THEN F.CD END) AS NUM_FEMALE
FROM MARC M LEFT JOIN
FUNCION F
ON M.CD_FUNCION = F.CD
GROUP BY M.TYPE;