2012-08-24 49 views
0

我使用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

在几个地方,你正在使用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
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