简体   繁体   English

SELECT CASE SQL中的DISTINCT COUNT

[英]DISTINCT COUNT in SELECT CASE SQL

I have a table of reports that include the fields Case (unique number), ISR (Individual Safety Report - unique number) and YearsOld . 我有一份报告表,其中包括Case (唯一编号), ISR (个人安全报告 - 唯一编号)和YearsOld

There can be more than one ISR for each Case. 每个案例可以有多个ISR。 I want to count the number of unique Cases within age groups. 我想计算年龄组中唯一案例的数量。

This SQL gives me a count of the number of ISRs: 这个SQL给了我一个ISR数量的计数:

SELECT  
COUNT(CASE WHEN `YearsOld` = -2) THEN 1 END) `No Report`,
COUNT(CASE WHEN `YearsOld` BETWEEN 0 AND 5) THEN 1 END) `0 to 5`
COUNT(CASE WHEN `YearsOld` BETWEEN 6 AND 12) THEN 1 END) `6 to 12`
FROM `Demographics`

is there a way to modify this to count the DISTINCT Cases for these Age Groups? 有没有办法修改这个来计算这些年龄组的DISTINCT Cases

If your "case" variable is unique, you can certainly put the distinct keyword in the SQL CASE syntax directly: 如果您的“case”变量是唯一的,您当然可以直接将distinct关键字放在SQL CASE语法中:

Count(distinct CASE when yearsold between 6 and 12 then case else null end)

That way, each unique value of the case variable is counted only once. 这样,case变量的每个唯一值只计算一次。

Just a note on column naming, I would suggest not using a word that has meaning in SQL if you have a choice (Ie use 'case_num' instead of case). 只是关于列命名的注释,如果你有选择的话,我建议不要使用在SQL中有意义的单词(即使用'case_num'而不是case)。

You could use a subquery to filter your demographics table for a single YearsOld field per case, although if that case might have been related to difference ages for different ISR it'll only end up being counted in one bracket (perhaps this is what you want?): 您可以使用子查询来过滤每个案例的单个YearsOld字段的人口统计表,但如果这种情况可能与不同ISR差异年龄相关,那么它最终只会被计入一个括号中(也许这就是您想要的?):

SELECT
  ... -- as you currently have
FROM (
  SELECT `Case`, `YearsOld` from `Demographics` GROUP BY `Case`
) t;

Alternatively, to "count" each "distinct" "case" within each bracket, you do literally that: 或者,为了“计算”每个括号内的每个“不同”“案例”,您确实按字面意思:

SELECT
  COUNT(DISTINCT CASE WHEN `YearsOld` = -2 THEN 1 END) `No Report`,
  COUNT(DISTINCT CASE WHEN `YearsOld` BETWEEN 0 AND  5 THEN `Case` END) `0 to 5`,
  COUNT(DISTINCT CASE WHEN `YearsOld` BETWEEN 6 AND 12 THEN `Case` END) `6 to 12`
FROM Demographics;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM