SQL - 与Case何时不同

时间:2016-09-05 08:30:41

标签: sql

当我使用以下查询时,它返回重复的外部ID,因为它将不同的情况列为不同的行。

SELECT DISTINCT

    OENT.OTHER_EXTERNAL_ID                                                                                                      AS 'Agent Master Number'       
   ,CASE WHEN SE.Organization_Name IS NULL OR RTRIM(LTRIM(SE.ORGANIZATION_NAME)) = '' THEN '' ELSE SE.ORGANIZATION_NAME END     AS 'Agent'

   GROUP BY

    OENT.OTHER_EXTERNAL_ID                                                                                              
    ,CASE WHEN SE.Organization_Name IS NULL OR RTRIM(LTRIM(SE.ORGANIZATION_NAME)) = '' THEN '' ELSE SE.ORGANIZATION_NAME END

我在哪里正确使用不同的,所以它将案例列为一行,无论它满足什么情况?

由于

问题是它一直在返回

AGENT_NUMBER    AGENT

MA12348677  DREHWING, DOUGLAS

MA12348677  DREHWING, DOUGLAS A

我希望这是一行,因为它们具有相同的AGENT_NUMBER

1 个答案:

答案 0 :(得分:0)

select distinct
OENT.OTHER_EXTERNAL_ID AS AGENT_NUMBER,
CASE 
    WHEN SE.Organization_Name IS NULL OR RTRIM(LTRIM(SE.ORGANIZATION_NAME)) = '' THEN '' 
    ELSE upper( SE.ORGANIZATION_NAME )
END AS AGENT
FROM SomeTableName
order by AGENT_NUMBER

如果代理编号不同,它仍将返回重复项。如果你想找到重复的名字,那么

select AGENT, count (AGENT_NUMBER) from (
    select OENT.OTHER_EXTERNAL_ID AS AGENT_NUMBER,
    CASE 
        WHEN SE.Organization_Name IS NULL OR RTRIM(LTRIM(SE.ORGANIZATION_NAME)) = '' THEN '' 
        ELSE upper( SE.ORGANIZATION_NAME )
    END AS AGENT
    FROM SomeTableName
    )
    group by AGENT
    HAVING count (AGENT_NUMBER) >1
    order by AGENT

查找相同代理编号的重复名称:

select AGENT_NUMBER, count (AGENT) from (
    select OENT.OTHER_EXTERNAL_ID AS AGENT_NUMBER,
    CASE 
        WHEN SE.Organization_Name IS NULL OR RTRIM(LTRIM(SE.ORGANIZATION_NAME)) = '' THEN '' 
        ELSE upper( SE.ORGANIZATION_NAME )
    END AS AGENT
    FROM SomeTableName
    )
    group by AGENT_NUMBER
    HAVING count (AGENT) >1
    order by AGENT_NUMBER