【问题标题】:How to group column value in different column and display it in different column如何将不同列中的列值分组并在不同列中显示
【发布时间】:2021-11-08 09:44:50
【问题描述】:

我有一个名为公司和公司对客户的回应的专栏。我需要选择具有三个值“已关闭”、“以解释关闭”和“以非货币救济关闭”的公司和公司对客户的响应。

我必须将其显示为 4 列公司,“关闭并解释”与“关闭”值,“关闭并解释”与“关闭并解释”值,“关闭并解释”与“关闭非货币救济” ' 价值。这就是我想要的

有谁知道我需要使用什么命令将其显示到 4 个不同的列中?

这是我目前的语法。它已经按公司分组,但我没有将其显示到不同的列中

select company, count(`Company Response to Consumer`)
from consumercomplaints
where `Company Response to Consumer` in ('Closed', 'Closed with explanation', 'Closed with non-monetary relief')
group by company

这是当前的输出

【问题讨论】:

    标签: mysql sql group-by mariadb


    【解决方案1】:

    您确实需要条件聚合。在 MySQL 中,这可以通过使用 sum(<boolean expression>) 进行最简单的处理:

    select company,
           sum(`Company Response to Consumer` = 'Closed') as num_closed,
           sum(`Company Response to Consumer` = 'Closed with explanation') as num_closed_with_explanation,
           sum(`Company Response to Consumer` = 'Closed with non-monetary relief') as num_closed_with_nonmonetary_relief
    from consumercomplaints
    where `Company Response to Consumer` in ('Closed', 'Closed with explanation', 'Closed with non-monetary relief')
    group by company;
    

    【讨论】:

      【解决方案2】:

      您可以在此处使用 case 表达式来创建列

      select 
          company, 
          SUM(CASE
              WHEN `Company Response to Consumer`='Closed' THEN 1
              ELSE 0
          END) as `Closed`,
          SUM(CASE
              WHEN `Company Response to Consumer`='Closed with explanation' THEN 1
              ELSE 0
          END) as `Closed with explanation`,
          SUM(CASE
              WHEN `Company Response to Consumer`='Closed with non-monetary relief' THEN 1
              ELSE 0
          END) as `Closed with non-monetary relief`
      from consumercomplaints
      where `Company Response to Consumer` in ('Closed', 'Closed with explanation', 'Closed with non-monetary relief')
      group by company
      

      注意。 where 子句在这里是可选的,因为 case 表达式提供了一个 0/1 值,当求和时,它会计算数据集中出现的次数。

      让我知道这是否适合你。

      【讨论】:

        猜你喜欢
        • 2023-04-10
        • 2021-11-08
        • 1970-01-01
        • 2022-08-09
        • 2017-09-05
        • 1970-01-01
        • 1970-01-01
        • 2022-01-14
        • 2014-04-28
        相关资源
        最近更新 更多