【问题标题】:Sql Query get summary countSql Query 获取汇总计数
【发布时间】:2020-10-22 08:41:22
【问题描述】:

我在 Oracle 中有下表

Fruit  | Color
-------+-------
Apple  | Red
Apple  | Green
Cherry | Red

我需要下面的总结,只有颜色不同的那些

Fruit | Colors
------+-------
Apple | 2

【问题讨论】:

    标签: sql oracle select group-by count


    【解决方案1】:

    只需使用聚合,在having 子句中使用过滤器:

    select fruit, count(*) colors
    from mytable
    group by fruit
    having count(*) > 1
    

    这假定(fruit, color) 上没有重复项,如您的示例数据所示。否则,您需要count(distinct color) 而不是count(*)

    select fruit, count(distinct color) colors
    from mytable
    group by fruit
    having count(distinct color) > 1
    

    【讨论】:

    • 有点扭曲.. 我们可以得到如下输出.. (列标题)水果|红色 |绿色 |黑色..(第 1 行)苹果 | 1 | 1 | 0
    【解决方案2】:

    这是一个group by,用于过滤聚合结果:

    select fruit, count(distinct color) as colors
    from the_table
    group by fruit
    having count(distinct color) > 1;
    

    count(distinct color) 中的 distinct 使它只计算每种水果的不同颜色。

    【讨论】:

      猜你喜欢
      • 2023-02-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-10
      • 1970-01-01
      • 2018-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多