【问题标题】:How do I count distinct values from same id?如何计算来自相同 ID 的不同值?
【发布时间】:2019-05-30 00:26:18
【问题描述】:

如果每个 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 种)。

【问题讨论】:

  • 你尝试了什么?为什么他们不工作?你说你试过DISTINCT,但这看起来完全符合你的需要。你写的声明是什么?我看不到DISTINCT 将如何为您提供的值返回 4 行(可能是因为您刚刚返回了 symptom 的值,但是如果您想要 ID,为什么不返回呢?) .

标签: sql sql-server


【解决方案1】:

你需要 distinctselect 声明:

select distinct id, Symptom
from table t;

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

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

【讨论】:

    【解决方案2】:

    只需按这些字段分组:

    SELECT ID, Symptom
    FROM Symptoms
    GROUP BY ID, Symptom
    

    小提琴:http://sqlfiddle.com/#!18/48dde/2/0

    【讨论】:

      【解决方案3】:

      试试这个:

      SELECT ID, Symptom
      FROM MY_TABLE
      GROUP BY 1,2
      

      【讨论】:

      • 您不能在GROUP BY 子句中使用序数位置(您实际上是在说按整数值12 分组)。此外,使用序数值通常是个坏主意:Bad habits to kick : ORDER BY ordinal
      • 另外,他并没有要求汇总。他只想要不同的组合。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-04
      • 2022-01-15
      • 1970-01-01
      • 1970-01-01
      • 2021-12-11
      相关资源
      最近更新 更多