How to Delete top 1 item after using CTE (Common Table Expression)

King Java 790 Reputation points
2025-04-15T19:23:50.7666667+00:00

I am trying to delete top 1* item after using CTE.

I have the bottom T-SQL statement which works fine with select statement on the second part.

with cte as
(
    select *, 
           email_cnt = count(*) over (partition by "User"),
		   duplicate_Yes =	case when count(AccessToAllLocations) over (partition by "User") > 1
									and 
									count("Location") over (partition by "User") > 1
                                then 1
                                else 0
                                end
    from   [dbo].[tblPBIGroup_CA]
)
select top 1*  from cte c
where  email_cnt > 1
and    duplicate_Yes = 1
order by DateLoad asc

But, I am trying to delete not select.

How do I modify to make it work?

Developer technologies Transact-SQL
0 comments No comments
{count} votes

Accepted answer
  1. Michael Taylor 60,161 Reputation points
    2025-04-15T20:04:13.21+00:00

    The CTE is running a query so you cannot delete from that. Use the Delete-Select syntax of SQL to delete from the table the results of running the query.

    ;WITH cte (...)
    DELETE FROM [tblPBIGroup_CA]
    FROM [tblPBIGroup_CA] t
    JOIN (SELECT TOP 1 * FROM cte...) c ON <key joining tblPBIGroup_CA to itself>
    
    2 people found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Erland Sommarskog 121.4K Reputation points MVP Volunteer Moderator
    2025-05-07T20:59:30.2666667+00:00

    It is not clear to me what you want to delete, but Michael is wrong. You can delete from the CTE (as long as SQL Server can map back to a single table). No need for the join.

    Maybe this is what you want:

    with cte as
    (
        select *, 
               email_cnt = count(*) over (partition by "User"),
    		   duplicate_Yes =	case when count(AccessToAllLocations) over (partition by "User") > 1
    									and 
    									count("Location") over (partition by "User") > 1
                                    then 1
                                    else 0
                                    end
        from   [dbo].[tblPBIGroup_CA]
    ), nextcte as (
       select top 1*  from cte c
       where  email_cnt > 1
       and    duplicate_Yes = 1
       order by DateLoad asc
    )
    delete nextcte
    
    1 person found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.