简体   繁体   中英

Select into Table from Table2 where column in (Subquery)

SELECT .... ColumnNames ...
INTO [FOUND_DUPLICATES] 
FROM [FIND_DUPLICATES] AS FD
WHERE FD.[Contract No] IN 
    (SELECT [Contract No],
            [Vehicle Identity number (VIN)],
            COUNT(*) AS Anzahl 
    FROM FIND_DUPLICATES
    GROUP BY 
            [Contract No],
            [Vehicle Identity number (VIN)]
    HAVING COUNT(*) >1)

Here u can see what I want :)

Find duplicates and copy them to another table. But with this code I get an error:

Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.

The SELECT statement to find the duplicates is working very well. But I have a problem to select and copy only the duplicates to the new table with Select Into.

I hope u can understand what I want and anyone can help me with that :)

//EDIT: Im using SQL Server 2008 R2

You can use this:

SELECT  .... ColumnNames ...

INTO [FOUND_DUPLICATES] 
FROM [FIND_DUPLICATES] AS FD
WHERE FD.[Contract No] IN
(
  SELECT 
    [Contract No]
  FROM FIND_DUPLICATES
  GROUP BY 
     [Contract No],
     [Vehicle Identity number (VIN)]
  HAVING COUNT(*) >1
)

or use correlated subquery:

SELECT .... ColumnNames ...

INTO [FOUND_DUPLICATES] 
FROM [FIND_DUPLICATES] AS FD
WHERE EXISTS 
(
    SELECT 1
    FROM FIND_DUPLICATES FD1
    WHERE FD.[Contract No] = FD1.[Contract No]
    GROUP BY 
        FD1.[Contract No],
        FD1.[Vehicle Identity number (VIN)]
    HAVING COUNT(*) >1
)

Adding another sub query should work?

Select  .... ColumnNames ...

INTO [FOUND_DUPLICATES] 
    FROM [FIND_DUPLICATES]
    AS FD
    where FD.[Contract No] 
       IN (  Select [Contract No] from (Select 
        [Contract No],
        [Vehicle Identity number (VIN)],
        COUNT(*) AS Anzahl 
    from FIND_DUPLICATES
    group by 
        [Contract No],
        [Vehicle Identity number (VIN)]
    having count(*) >1)x)
Select  .... ColumnNames ...

INTO [FOUND_DUPLICATES] 
    FROM [FIND_DUPLICATES]
    AS FD
    where FD.[Contract No] 
       IN (
       select [Contract No] from (Select --inner sub query 
        [Contract No],
        [Vehicle Identity number (VIN)],
        COUNT(*) AS Anzahl 
    from FIND_DUPLICATES
    group by 
        [Contract No],
        [Vehicle Identity number (VIN)]
    having count(*) >1) )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM