【问题标题】:How to combine and count multiple rows with different values using SQL如何使用 SQL 组合和计算具有不同值的多行
【发布时间】:2015-07-20 19:19:23
【问题描述】:

我见过多种场景,您将多行与相同的值组合在一起,但无法找到任何可以将多行与不同的值组合在一起的地方。如果我有一个包含来源和随附日期的表格,我想获取每个来源的日期计数,然后按选择的几个值对来源进行分组。示例如下:

当前

  Source                Count
  Yahoo                 10
  Bing                  15
  Google                12
  Paid                  10
  Organic               15  

需要

  Source                Count
  Media                 37
  Paid                  10
  Organic               15

【问题讨论】:

  • 如果您没有其他分组并且可以接受硬编码,请使用 case 语句。

标签: mysql sql


【解决方案1】:
SELECT case when source in ('Yahoo','Bing','Google') then 'Media' 
            else Source end as Source,  sum(count) as count
GROUP BY case when source in ('Yahoo','Bing','Google') then 'Media' 
            else Source end 

【讨论】:

    【解决方案2】:
    select case when source not in ('Paid','Organic') 
                then 'Media'
                else source
           end as my_source, 
           count(*)
    from your_table
    group by my_source
    

    【讨论】:

      【解决方案3】:

      人们发表的大部分内容都是正确的。 但是他们因为“计数”而感到有些困惑,他们认为它是一个函数而不是一个变量。 根据您的数据,您正在衡量和分组营销来源。

      这是您需要的查询。

          select 
      case 
      when Source  in ('Yahoo','Bing','Google') then 'Media'
      else Source
      end as 'Source',
      case 
      when Source  in ('Yahoo','Bing','Google') then (Select sum(Count) from your_table where source in  in ('Yahoo','Bing','Google'))
      else Count
      end as 'Count'
      from your_table
      group by 'Source'
      

      【讨论】:

        【解决方案4】:

        此方法比发布的其他方法略有改进,因为它将分组逻辑放入外部应用,并使用“”运算符,以便它引用基本查询。这允许在一个地方声明和维护逻辑,从而使代码更易于阅读。不确定 MySQL 是否支持 "" 运算符,但值得一试...

        select [Source Group], 
               count(*)
        from your_table as S
        outer apply (select case when s.source not in ('Paid','Organic') 
                    then 'Media'
                    else s.source
                    end 
                as [Source Group])_ 
        group by [Source Group]
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-02-24
          • 1970-01-01
          • 2014-03-01
          • 2011-03-12
          • 1970-01-01
          • 1970-01-01
          • 2021-11-21
          • 1970-01-01
          相关资源
          最近更新 更多