[英]Delete from statement using aggregates in HAVING clause SQL Server 2008
I have a table that looks like the following 我有一张看起来像下面的桌子
where what should be a unique identifier,drg, is not, so I started on the personal challenge of fixing it. 唯一的标识符drg没有出现,因此我开始着手解决它。 I could do this easily a myriad of ways but I'm trying to do some things in a different fashion to learn some new techniques. 我可以通过多种方式轻松完成此操作,但是我正在尝试以不同的方式做一些事情来学习一些新技术。 What needs to be deleted from the table is any row whose drg is not unique and whose eff_date is **less than ** the max eff_date. 需要从表中删除的是drg 不是唯一且eff_date小于最大eff_date的任何行。
To find what I needed I used 找到我需要的东西
select d1.drg, MAX(d1.eff_date) as maxEffDate,d2.drgdesc
from drgtable d1
inner join drgtable d2 on d1.drg=d2.drg
group by d1.drg,d2.drgdesc
having MAX(d1.eff_date) = MAX(d2.eff_date)
Instead of just selecting this into a new table and dropping the old one, I'd like to do it in a delete statement. 我不只是将其选择到新表中并删除旧表,而是希望在delete语句中执行此操作。
My though process on the strange looking query below was to find the rows that weren't in the table from the above query I used and delete them. 我对下面看起来很奇怪的查询进行的虽然处理是从上面使用的查询中查找表中未包含的行并将其删除。 I got close, but am stuck. 我靠近了,但是被卡住了。 Also, if there's a way easier way to do this, please let me know. 另外,如果有更简便的方法可以进行此操作,请告诉我。 Thanks 谢谢
--the purpose of this was to find the rows in d3 that were not in d4 and delete them. -目的是在d3中找到不在d4中的行并将其删除。 didn't quite get that far 还没走那么远
delete from
drgtable
where
(
select * from drgtable as d3
left join
(
select d1.drg, MAX(d1.eff_date) as maxEffDate,d2.drgdesc
from drgtable d1
inner join drgtable d2 on d1.drg=d2.drg
group by d1.drg,d2.drgdesc
having MAX(d1.eff_date) = MAX(d2.eff_date)
) d4 on d4.drg =d3.drg and d4.maxEffDate = d3.eff_date and d3.drgdesc = d4.drgdesc
)
This should work: 这应该工作:
;WITH cte As
(
SELECT *,
MAX(eff_date) OVER(partition by drg) as MaxEffDate
FROM drgtable
)
DELETE
FROM cte
WHERE eff_date <> MaxEffDate
Plus, plenty of new tricks in there for you to learn. 另外,还有许多新技巧可供您学习。 :-) :-)
(note: this does assume that you are on SQL Server 2005 or higher) (注意:这确实假定您使用的是SQL Server 2005或更高版本)
If I understand your correct, you need smth like this? 如果我理解您的正确,您是否需要像这样的东西?
delete drgtable
from drgtable as d1
where exists
(
select t.*
from drgtable as t where t.drg = d1.drg and t.eff_date > d1.eff_date
)
Could you try: 您可以尝试:
delete from drgtable
where DRG+MaxEffDate
not in
(Select drg+maxEffDate as Combo
FROM
(select d1.drg,
MAX(d1.eff_date) as maxEffDate,
d2.drgdesc
from drgtable d1
inner join drgtable d2
on d1.drg=d2.drg
group by d1.drg,d2.drgdesc
having MAX(d1.eff_date) = MAX(d2.eff_date) ) as RecordsToKeep
)
-- assuming there are no nulls in the data
? ? I realize this might be a bit hack-ish and there may be more eloquent solutions but this should work. 我意识到这可能有点hacking,可能会有更雄辩的解决方案,但这应该可行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.