有没有办法在嵌套的 WITH 语句中包含 DELETE FROM 语句?

Posted

技术标签:

【中文标题】有没有办法在嵌套的 WITH 语句中包含 DELETE FROM 语句?【英文标题】:Is there a way to include a DELETE FROM statement in a nested WITH statement? 【发布时间】:2021-10-26 18:38:09 【问题描述】:

我试图通过创建另一个表来删除重复项,但我无法包含 delete from 语句。我在 SQL Server 中有代码,但我正在尝试将其转换为 Oracle。我尝试将 select 替换为 delete from 但出现错误:缺少 SELECT 关键字。

代码如下:

WITH RowNumCTE AS(
SELECT t.* ,
    ROW_NUMBER() OVER (
    PARTITION BY ParcelID,
                PropertyAddress,
                SalePrice,
                SaleDate,
                LegalReference
                ORDER BY
                    UniqueID
                    ) t
                    
FROM nashvillehousing t
--Order by parcelid;
) 
SELECT *
FROM RowNumCTE
WHERE t > 1;

这里是示例数据:

https://github.com/AlexTheAnalyst/PortfolioProjects/blob/main/Nashville%20Housing%20Data%20for%20Data%20Cleaning.xlsx

预期结果应该是 104 个删除的重复条目。

【问题讨论】:

Oracle 不支持使用 With 子句删除。请发布您的示例数据和预期结果。 嗨 Ankit,我发布了示例数据和预期结果 请发布几行有问题的数据,而不是作为链接。 【参考方案1】:

您可以在 ROWID 伪列上关联:

DELETE FROM nashvillehousing
WHERE ROWID IN (
  SELECT ROWID
  FROM   (
    SELECT ROW_NUMBER() OVER (
             PARTITION BY ParcelID, PropertyAddress, SalePrice, SaleDate, LegalReference
             ORDER BY UniqueID
           ) AS rn       
    FROM nashvillehousing
  )
  WHERE  rn > 1
)

如果你真的想使用子查询分解子句 (WITH) 那么:

DELETE FROM nashvillehousing
WHERE ROWID IN (
  WITH sqfc (rn) AS (
    SELECT ROW_NUMBER() OVER (
             PARTITION BY ParcelID, PropertyAddress, SalePrice, SaleDate, LegalReference
             ORDER BY UniqueID
           )
    FROM nashvillehousing
  )
  SELECT ROWID
  FROM   sqfc
  WHERE  rn > 1
)

【讨论】:

以上是关于有没有办法在嵌套的 WITH 语句中包含 DELETE FROM 语句?的主要内容,如果未能解决你的问题,请参考以下文章

如何在选择案例语句中包含数字和字符串

在我的 Mysql 语句中包含 GROUP BY id

有没有办法在咖啡脚本中包含文件?

有没有办法在 C# 程序中包含 C++ 命令? [复制]

有没有办法在 emscripten 中包含自定义标题?

Swift - 有没有办法在连接字符串中包含单引号(')?