簡體   English   中英

返回一列中值相等而另一列中值不同的行

[英]Return rows that have the equal values in a column but a different value in another column

我正在嘗試返回符合此條件的結果

  • 具有2個不同ColorCode相同ProfileType

我當前的查詢返回所有ProfileTypes和ColorCodes

ProfileType | ColorCode

SPT1        | 8XYZ
SPT1        | 1XYZ
SPT2        | 4XYZ
SPT2        | 4XYZ
SPT3        | 4XYZ
SPT3        | 9XYZ
SPT4        | 4XYZ
SPT4        | 4XYZ

我只想從上述結果集中返回這些行,因為它們是相同的ProfileType,但是具有兩個不同的ColorCodes

ProfileType | ColorCode
SPT1        | 8XYZ
SPT1        | 1XYZ
SPT3        | 4XYZ
SPT3        | 9XYZ

詢問

SELECT. P.ProfileType, E.ColorCode,
FROM profilegroups AS PG
 INNER JOIN mfg.profiles AS P
         ON PG.id = P.pickgroup
 INNER JOIN exts AS E
         ON E.Profile = P.Profile
        AND E.ProductNumber IN ('XYZ123', 'MX231X')
        AND PG.DoProcess = 1 
        AND P.ProfileType IN ('SPT1','SPT2','SPT3','SPT4','SPTX2','SPT31', 'SPT90');

ProfileGroups
    - id
Profiles 
    - Profile 
    - ProfileType 
    - PickGroup
Exts
    - Profile 
    - ColorCode

Profiles和Exts有一個主鍵Profile,它與Profiles不同,后者來自Profiles表。

加入一個子查詢,該子查詢獲取每種配置文件類型的不同顏色代碼的數量,但僅返回具有一個以上顏色代碼的顏色代碼:

SELECT profileType
FROM Exts
GROUP BY profileType
HAVING COUNT(DISTINCT colorCode) > 1

完整的查詢將如下所示:

SELECT. ProfileType, Color,
FROM profilegroups AS PG
 INNER JOIN mfg.profiles AS P
         ON PG.id = P.pickgroup
 INNER JOIN exts AS E
         ON E.ProfileType = P.ProfileType
 INNER JOIN (
    SELECT profile
    FROM Exts
    GROUP BY profile
    HAVING COUNT(DISTINCT colorCode) > 1) M 
        ON M.profile = P.profile
WHERE   E.ProductNumber IN ('XYZ123', 'MX231X')
        AND PG.DoProcess = 1 
        AND P.ProfileType IN ('SPT1','SPT2','SPT3','SPT4','SPTX2','SPT31', 'SPT90')

嘗試這個 :

select profileType, colorCode
from (select distinct profileType, colorCode from table) a
group by profileType
having count(*) > 1;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM