使用 group by 进行 SQL Server 更新

标签 sql sql-server-2008 group-by sql-update

 insert into tableA (column1) 
 select min(tableC.column1)
 from tableB 
 inner join tableC on (tableC.coumn2 = tableB.column1
 and tableB.column2 = tableA.column2) 
 group by tableA.column2

我将如何根据标准将上述内容更改为使用 group by 的更新而不是使用 group by 插入 tableB.column2 = tableA.column2 ?

请注意,我正在使用 SQL SERVER 2008.

最佳答案

  Update A set Column1 = minC    
    from (select Ab.Column2, min(C.Column1) as minC
            from A Ab
            inner join B on Ab.Column2 = B.Column2
            inner join C on C.column2 = B.Column2 --No need to add again the A.col2 = B.col2
            group by Ab.Column2) Grouped where A.Column2 = Grouped.Column2

这是你想要的吗?
这将为每个 columnA 获得 C.Column1最小值,并将在 A.Column1 中更新它(这是您之前插入的位置),基于条件 A.Column2 = Grouped.Column2 .

这是一个 SQL-Fiddle Demo

关于使用 group by 进行 SQL Server 更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12343437/

相关文章:

sql - Postgres/ANSI SQL 系统如何将 'count' 聚合与 GROUP BY 字段相关联

sql - 优化内部连接

sql - 如何用下一行中的第一个非零值更新零?

sql-server - SSIS 集合中的通配符{不包括}名称 xlsx

sql-server-2008 - 用于在 SQL Server 2008(R1) 上部署的 SQL Server 2008R2 SSIS 包

mysql - 最新Group By MYSQL+链接表

mysql - 使用mysql查询来填充空表的行

php - 基于具有 LIMIT 限制的 SELECT 查询的 MYSQL INSERT 查询

sql - IsNull() sql 函数

python - 使用字典进行数据帧聚合