首页 > 解决方案 > 如何计算来自相同 ID 的不同值?

问题描述

如果每个 ID 有一些重复项,我如何计算列中的不同值?

我尝试了 COUNT、DISTINCT、CASE 和所有方法,但我无法计算每个 ID 的不同值。我有一张这样的桌子。

ID          Symptom
1           Headache
1           Headache
1           Hematuria
1           Leg pain
1           Headache
2           Cough
2           Headache
2           Cough
3           Cough
3           Cough
3           Cough

我想得到这样的东西。

ID    Symptom 
1     Headache
1     Hematuria
1     Leg pain
2     Cough
2     Headache
3     Cough

或者我如何获得总数?就像有 5 种不同的症状,但没有 11 种症状(如果我使用 DISTINCT,我会得到 4 种)。

标签: sqlsql-server

解决方案


你需要distinctwithselect声明:

select distinct id, Symptom
from table t;

如果您需要唯一计数,请在内部使用它count()

select id, count(distinct Symptom)
from table t
group by id;

推荐阅读