【问题标题】:How to access the value of a function generated column in SQL如何在 SQL 中访问函数生成列的值
【发布时间】:2011-07-01 23:05:04
【问题描述】:

我有以下 SQL

从 TempTable 中选择 count(*) col、column1、column2、column3 按 column1、column2、column3 分组 按 1 desc 排序

所以计数生成的列将返回一个数字,并且有 17 行没有数字 1(重复行,因为第 1、2 和 3 列是主键),我想删除任何有计数的行大于 1?

【问题讨论】:

  • 如何防止删除所有记录?您只需要删除额外的记录,并保持一条完整(以及哪一条?),这将很难,这就是为什么您应该在表上定义完整性约束。试图清理不良的完整性并不总是那么简单。
  • 目前我只需要删除错误记录,只是寻求快速修复,而不是解决方案!

标签: sql


【解决方案1】:

你可以使用have子句:

select count(*) col, column1, column2, column3
from TempTable group by column1, column2, column3
having count(*) > 1
order by 1 desc

删除:

delete tt
from TempTable tt
     inner join (select count(*) col, column1, column2, column3
                 from TempTable group by column1, column2, column3
                 having count(*) > 1) tmp
     on tmp.column1 = tt.column1
     and tmp.column2 = tt.column2
     and tmp.column3 = tt.column3

【讨论】:

  • 我如何应用这个来删除,删除所有计数大于 1 的记录?
  • @Grace:我已经用一个例子编辑了我的答案。基本上你可以使用连接删除。
【解决方案2】:

首先将数据插入到临时表中:

select count(*) col, column1, column2, column3
into #temp
from TempTable group by column1, column2, column3 order by 1 desc

然后,您删除数据,并将其从#temp 表中插入:

delete from TempTable 
go

insert into TempTable select column1, column2, column3 from #temp
go

【讨论】:

    猜你喜欢
    • 2020-08-01
    • 1970-01-01
    • 2012-09-16
    • 2018-10-30
    • 1970-01-01
    • 2021-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多