2012-08-24 86 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