2014-02-17 49 views
0

我有一個包含這些列的表:SQL - 找到一個列有重複值的行

Nameplate 
Model 
Segment 

樣本表如下所示:

Nameplate Model Segment 
Acura  ILX Small Lux Car 
Audi  Q5  Compact Lux Car 
Audi  Q5  Mid Lux Car 
Audi  SQ5 Compact Lux Car 

我需要找到所有Nameplate, Model組合,帶多個Segments

在上表中,我需要它返回:

Audi  Q5  Compact Lux Car 
Audi  Q5  Mid Lux Car 

我想下面將工作:

SELECT DISTINCT 
    [Nameplate], [Model], [Segment] 
FROM 
    dbo.[Weighted Extract] 
GROUP BY 
    [Nameplate], [Model], [Segment] 
HAVING 
    COUNT([Segment]) > 1; 

上面的代碼只能與多個Nameplate, ModelSegment行返回組合。這應該比我製作更容易,但我卡住了。

回答

-1

試試這個:

SELECT [Nameplate], [Model] 
FROM dbo.[Weighted Extract] 
GROUP BY [Nameplate], [Model] 
HAVING COUNT(distinct [Segment]) > 1; 
+0

根據需要不返回「Segment」列。 –

+0

就是這樣!我正試圖將Segment添加到SELECT語句,並且它是錯誤的。感謝您及時的回覆。 – user3319605

+0

@Martin - 你是對的,但Kaidjin的代碼至少可以告訴我重複的地方。顯示細分會很好,但對於我現在的需求並不重要。 – user3319605

4

您可以使用EXISTS

SELECT [Nameplate], [Model], [Segment] 
FROM dbo.[Weighted_Extract] we1 
WHERE EXISTS 
(
    SELECT 1 FROM dbo.[Weighted_Extract] we2 
    WHERE we1.Nameplate = we2.Nameplate 
    AND we1.Model = we2.Model 
    AND we1.Segment <> we2.Segment 
); 

Demo

1

試試這個,這應該從SQLSERVER工作2005+:

;WITH X AS 
(
    SELECT [Nameplate], [Model], [Segment], 
     count(*) over (partition by [Nameplate], [Model]) cnt 
    FROM dbo.[Weighted Extract] 
) 
SELECT [Nameplate], 
     [Model], 
     [Segment] 
FROM X 
WHERE cnt > 1