从 SQL UNION 查询中删除重复行

Remove duplicate rows from SQL UNION Query

我尝试从以下联合查询中删除重复行:

SELECT DISTINCT c.Cat_Name, s.SubCat_DisplayName, st.State, COUNT(a.SubCategory_ID) as SubCount
FROM CT_SubCategory s
INNER JOIN CT_Category c ON s.Cat_ID=c.Cat_ID
INNER JOIN CT_AdvertiserSubcategory a ON s.Subcat_ID = a.SubCategory_ID
INNER JOIN CT_AdvertiserCity ac ON ac.UserID = a.UserID
INNER JOIN CT_City ci ON ci.City_ID = ac.City_ID
INNER JOIN CT_State st ON ci.State_ID = st.State_ID
WHERE ci.CityName LIKE 'Grand-Rapids' AND st.Abbr = 'MI'
GROUP BY c.Cat_Name, s.SubCat_Name, s.SubCat_DisplayName, st.State
UNION
SELECT c.Cat_Name, s.SubCat_Name, s.SubCat_DisplayName, null, null
FROM CT_SubCategory s
INNER JOIN CT_Category C ON s.Cat_ID = c.Cat_ID
ORDER BY SubCat_DisplayName

当前结果:

Auto, Auto Repair, null, null
Auto, Auto Repair, Michigan, 3
Entertainment, Events, null, null
Gifts, Flowers, null, null

期望的结果:

Auto, Auto Repair, Michigan, 3
Entertainment, Events, null, null
Gifts, Flowers, null, null

我想从结果集中删除包含空值的重复自动修复行。

这可能与联合查询有关吗?

根据我的理解,你根本不需要 UNION 你必须使用 LEFT OUTER JOIN;

SELECT DISTINCT c.Cat_Name, s.SubCat_DisplayName, st.State, COUNT(a.SubCategory_ID) as SubCount
FROM CT_SubCategory s
INNER JOIN CT_Category c ON s.Cat_ID=c.Cat_ID
LEFT OUTER JOIN CT_AdvertiserSubcategory a ON s.Subcat_ID = a.SubCategory_ID
LEFT OUTER JOIN CT_AdvertiserCity ac ON ac.UserID = a.UserID
LEFT OUTER JOIN CT_City ci ON ci.City_ID = ac.City_ID
LEFT OUTER JOIN CT_State st ON ci.State_ID = st.State_ID
WHERE ISNULL(ci.CityName,'Grand-Rapids') LIKE 'Grand-Rapids' AND ISNULL(st.Abbr,'MI') = 'MI'
GROUP BY c.Cat_Name, s.SubCat_Name, s.SubCat_DisplayName, st.State

结果应该是这样的:

Auto, Auto Repair, Michigan, 3
Entertainment, Events, null, null
Gifts, Flowers, null, null

Farhang 的回答还可以。但是正确的查询写法是把where条件放在on子句中:

SELECT DISTINCT c.Cat_Name, s.SubCat_DisplayName, st.State,
       COUNT(a.SubCategory_ID) as SubCount
FROM CT_SubCategory s INNER JOIN
     CT_Category c
     ON s.Cat_ID = c.Cat_ID LEFT OUTER JOIN
     CT_AdvertiserSubcategory a
     ON s.Subcat_ID = a.SubCategory_ID LEFT OUTER JOIN
     CT_AdvertiserCity ac
     ON ac.UserID = a.UserID LEFT OUTER JOIN
     CT_City ci
     ON ci.City_ID = ac.City_ID AND
        ci.CityName = 'Grand-Rapids' LEFT OUTER JOIN
     CT_State st
     ON ci.State_ID = st.State_ID AND
        st.Abbr = 'MI'
GROUP BY c.Cat_Name, s.SubCat_Name, s.SubCat_DisplayName, st.State;

ISNULL()(或者我更喜欢 COALESCE())如果 CityNameAbbr 在数据中曾经 NULL,则 returns 意想不到的结果.对于 left join 中右侧 table 的过滤,您应该将条件放在 on 子句中。