如何选择2个字段区分

时间:2012-06-04 19:32:42

标签: sql database group-by distinct

我需要能够只选择除了所有这些之外还有IsActive = 1的记录:

SELECT DISTINCT 0 as CommunityID,  

                    CASE Libname
                        WHEN 'RKHL' THEN 'ROCK HILL'
                        WHEN 'FTML' THEN 'FORT MILL'
                        WHEN 'LANC' THEN 'LANCASTER'
                        WHEN 'BREV' THEN 'BREVARD'
                        WHEN 'PBTC' THEN 'MIDLANDS-CLEC'
                        WHEN 'PBTI' THEN 'MIDLANDS-ILEC'

                    END AS CommunityDesc,

                    LibName,
                    LibName + '|' AS FilterByID,
                    IsActive 
                    FROM Reference.dbo.Community
                    WHERE LibName <> 'CAROTEL' 
                    UNION
                    SELECT CommunityID, RTRIM(COMMNAME) AS CommunityDesc, LibName, LibName + '|' + RTRIM(COMMNAME) AS FilterByID, IsActive
                    FROM Reference.dbo.Community 

                    WHERE LibName <> 'CAROTEL'
                    ORDER BY 1,3;

2 个答案:

答案 0 :(得分:1)

IsActive=1添加到联盟两侧的WHERE子句中。

答案 1 :(得分:1)

您可以这种方式过滤结果集:

 SELECT * 
    FROM (
    SELECT DISTINCT 0 as CommunityID,  

                    CASE Libname
                        WHEN 'RKHL' THEN 'ROCK HILL'
                        WHEN 'FTML' THEN 'FORT MILL'
                        WHEN 'LANC' THEN 'LANCASTER'
                        WHEN 'BREV' THEN 'BREVARD'
                        WHEN 'PBTC' THEN 'MIDLANDS-CLEC'
                        WHEN 'PBTI' THEN 'MIDLANDS-ILEC'

                    END AS CommunityDesc,

                    LibName,
                    LibName + '|' AS FilterByID,
                    IsActive 
                    FROM Reference.dbo.Community
                    WHERE LibName <> 'CAROTEL' 
                    UNION
                    SELECT CommunityID, RTRIM(COMMNAME) AS CommunityDesc, LibName, LibName + '|' + RTRIM(COMMNAME) AS FilterByID, IsActive
                    FROM Reference.dbo.Community 

                    WHERE LibName <> 'CAROTEL'
) i
WHERE IsActive = 1
ORDER BY 1,3;