Cross Join始终使用相同的字符串消息

时间:2012-08-24 13:46:47

标签: sql-server-2005 duplicates cross-join having-clause

我使用的是Microsoft SQL Server 2005。

我希望在输出中有一个表,其中包含一个关于交叉连接中重复值的列,其中一个表只包含一个具有相同字符串消息的列。 我认为交叉连接带有“字符串消息”应该是正确的方法。

为什么以下脚本无效?

DECLARE @IN_CodesTable TABLE
   (
        CodesValues           NVARCHAR(60)
   )
INSERT INTO @IN_CodesTable VALUES('CODE_BB^&')
INSERT INTO @IN_CodesTable VALUES('CODE_1234')
INSERT INTO @IN_CodesTable VALUES('CODE_BB^&')
INSERT INTO @IN_CodesTable VALUES('CODE_$%^&')
INSERT INTO @IN_CodesTable VALUES('CODE_BB^&')
INSERT INTO @IN_CodesTable VALUES('CODE_BB^&')
INSERT INTO @IN_CodesTable VALUES('CODE_1234')

SELECT *
FROM   
(
SELECT DISTINCT CodesTable
FROM @IN_CodesTable
WHERE CodesTable IN
                    ( SELECT  CodesValues
                    FROM     @IN_CodesTable
                    GROUP BY CodesTable
                    HAVING   COUNT(*) > 1
                    )
)
CROSS JOIN
( 
    SELECT 'You have duplicates!' AS DupMessage
)

2 个答案:

答案 0 :(得分:2)

在某些地方,您使用CodesTable代替CodesValues。此外,虽然CROSS JOIN有效,但只需选择DupMessage作为附加值就更清楚了,例如:

SELECT *, 'You have duplicates!' AS DupMessage
FROM (
    SELECT DISTINCT CodesValues
    FROM IN_CodesTable
    WHERE CodesValues IN (
        SELECT  CodesValues
        FROM IN_CodesTable
        GROUP BY CodesValues
        HAVING COUNT(*) > 1
    )
 ) X

SqlFiddle here

答案 1 :(得分:1)

DECLARE @IN_CodesTable TABLE ( CodesValues NVARCHAR(60) ) 
INSERT INTO @IN_CodesTable VALUES
  ('CODE_BB^&'), ('CODE_1234'), ('CODE_BB^&'), ('CODE_$%^&'),
  ('CODE_BB^&'), ('CODE_BB^&'), ('CODE_1234') 

-- Display only values with duplicate rows.
select distinct CodesValues
  from @IN_CodesTable as CT
  where ( select count(42) from @IN_CodesTable where CodesValues = CT.CodesValues ) > 1

select distinct CodesValues
  from @IN_CodesTable as CT
  group by CodesValues
  having count(42) > 1

-- Display all values with duplicates indicated.
select distinct CodesValues,
  case when ( select count(42) from @IN_CodesTable where CodesValues = CT.CodesValues ) > 1 then 'Duplicates' else '' end as Flag
  from @IN_CodesTable as CT

select distinct CodesValues,
  case when count(42) > 1 then 'Duplicates' else '' end as Flag
  from @IN_CodesTable as CT
  group by CodesValues