从表2中选择表格(子查询中的列)

时间:2014-04-02 13:44:28

标签: sql sql-server select select-into

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)

在这里你可以看到我想要的东西:)

查找重复项并将其复制到另一个表中。 但是使用这段代码我得到一个错误:

  

当选择列表中只能指定一个表达式时   子查询不是用EXISTS引入的。

查找重复项的SELECT语句运行良好。但是我有一个问题就是选择并仅使用Select Into将副本复制到新表中。

我希望你能理解我想要的东西,任何人都可以帮助我:)

//编辑: 我正在使用SQL Server 2008 R2

3 个答案:

答案 0 :(得分:0)

您可以使用:

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
)

或使用相关子查询:

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
)

答案 1 :(得分:0)

添加另一个子查询应该有效吗?

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)

答案 2 :(得分:0)

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) )