我有一个包含这些列的表:
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, Model
和Segment
行的组合。这应该比我做的容易,但是我被卡住了。
答案 0 :(得分: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
);
答案 1 :(得分: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
答案 2 :(得分:-1)
试试这个:
SELECT [Nameplate], [Model]
FROM dbo.[Weighted Extract]
GROUP BY [Nameplate], [Model]
HAVING COUNT(distinct [Segment]) > 1;