【问题标题】:Merge multiple rows to one row based on same key基于相同的键将多行合并为一行
【发布时间】:2019-09-30 07:51:25
【问题描述】:

我有以下数据集:

key       column1  column2  column3
20171021  1        0        0
20171021  0        1        0
20171021  0        0        1

如您所见,所有行的键都是相同的。

我需要以下输出:

key       column1  column2  column3
20171021  1        1        1

谁能帮我写一个 sql 语句来完成这个?

【问题讨论】:

    标签: sql sql-server stored-procedures sql-server-2016


    【解决方案1】:

    这看起来像一个简单的聚合查询:

    SELECT [key], MAX(column1) column1, MAX(column2) column2, MAX(column3) column3
    FROM mytable
    GROUP BY [key]
    

    注意:我使用了聚合函数MAX(),但鉴于您的示例数据,它也可能是您需要的SUM();选择适合您的用例。

    【讨论】:

      【解决方案2】:

      使用聚合

      select [key], max(ccolumn1),max(column2) ,max(colum3) from table group by [key]
      

      【讨论】:

        【解决方案3】:

        您可以使用max() and group by 来实现此目的。

        select [key], max(column1), max(column2), max(column3) from tableA group by [key]
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-11-08
          • 2021-10-23
          • 1970-01-01
          • 1970-01-01
          • 2016-05-25
          • 1970-01-01
          • 2023-03-07
          相关资源
          最近更新 更多