从SQL UNION Query中删除重复的行

时间:2015-01-24 00:09:16

标签: sql sql-server union

我有以下联合查询,我试图从以下位置删除重复的行:

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

我想从结果集中删除带有空值的重复“自动修复”行。

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

2 个答案:

答案 0 :(得分:1)

我理解了这个问题,你根本不需要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

答案 1 :(得分:0)

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())如果数据中CityNameAbbrNULL,则会返回意外结果。要在left join中对右侧表格进行过滤,您应该将条件放在on子句中。