如何在同一个表中返回与变量计数匹配的行?

时间:2017-06-30 21:45:12

标签: sql-server

我有以下查询给出了TOP 10行,我想更改它只返回带有变量计数的行,在这种情况下,变量计数为2(QCAHLSWMTPL和QCAHLSWMTPLZ),怎么能我改变了吗?如何获得独特的变体计数?

SELECT TOP 10 SoftwareImageBuild si, variant 
FROM ODS.buildinfrastructure.SoftwareImageBuilds bsi
JOIN masterdata.softwareimages msi 
    ON msi.softwareimageid = bsi.SoftwareImageID
WHERE msi.SoftwareImage = 'WLAN.HL.2.0' AND 
    (BuiltBy = 'username1' OR BuiltBy = 'username2') and 
    Status !='Expired' 
ORDER BY Builton DESC

enter image description here

1 个答案:

答案 0 :(得分:0)

加入子查询,返回每个软件映像所具有的变体数量,另一个查询获取所有软件映像中的变体数量。

SELECT TOP 10 SoftwareImageBuild si, variant 
FROM ODS.buildinfrastructure.SoftwareImageBuilds bsi
CROSS JOIN (SELECT COUNT(Distinct variant) all_variants
            FROM ODS.buildinfrastructure.SoftwareImageBuilds) av
JOIN masterdata.softwareimages msi 
    ON msi.softwareimageid = bsi.SoftwareImageID
JOIN (SELECT SoftwareImageBuild si, COUNT(*) variant_count
      FROM ODS.buildinfrastructure.SoftwareImageBuilds
      GROUP BY SoftwareImageBuild) bsi2
    ON bsi.SoftwareImageBuild = bsi2.si AND bsi2.variant_count = av.all_variants
WHERE msi.SoftwareImage = 'WLAN.HL.2.0' AND 
    (BuiltBy = 'username1' OR BuiltBy = 'username2') and 
    Status !='Expired' 
ORDER BY Builton DESC