NULL字段的重复记录计数 - 有更好的方法吗?

时间:2013-03-01 15:29:29

标签: sql sql-server sql-server-2008

我需要根据特定列获得重复记录计数。如果字段具有NULL值,则 NOT 将其视为重复。

SELECT  Leadid,COUNT(Lead)
FROM    #CheckNULLCOUNT
GROUP   BY LeadId,Lead

但是使用以下查询它认为是重复的

 SELECT  Leadid,COUNT(ISNULL(Lead,'-'))
    FROM    #CheckNULLCOUNT
    GROUP   BY LeadId,Lead

我的问题是有更好的方法来获得NULL列的重复计数。

/* Create Temporary Table*/
 CREATE table #CheckNULLCOUNT(
    Id Int PRIMARY key
    ,name varchar(100) 
    ,LeadId Int
    ,Lead varchar(100))

    /* Insert data into temporary Table*/

INSERT INTO #CheckNULLCOUNT VALUES(1,'Skip',101,'lead1')
INSERT INTO #CheckNULLCOUNT VALUES(2,'Turner',102,'lead2')
INSERT INTO #CheckNULLCOUNT VALUES(3,'Molisa',103,'lead3')
INSERT INTO #CheckNULLCOUNT VALUES(4,'Mario',104,'lead4')
INSERT INTO #CheckNULLCOUNT VALUES(5,'Jack',105,'lead5')
INSERT INTO #CheckNULLCOUNT VALUES(6,'Kris',106,'lead6')
INSERT INTO #CheckNULLCOUNT VALUES(7,'John',107,'lead7')
INSERT INTO #CheckNULLCOUNT VALUES(8,'Owen',109,NULL)
INSERT INTO #CheckNULLCOUNT VALUES(9,'Bill',109,NULL)
INSERT INTO #CheckNULLCOUNT VALUES(10,'Martin',109,NULL)
INSERT INTO #CheckNULLCOUNT VALUES(11,NULL,111,'lead9')
INSERT INTO #CheckNULLCOUNT VALUES(12,NULL,111,'lead9')

 /* **NOT** treating as duplicate */
SELECT  Leadid,COUNT(ISNULL(Lead,'-'))
FROM    #CheckNULLCOUNT
GROUP   BY LeadId,Lead


/* treating as duplicate */

SELECT  Leadid,COUNT(ISNULL(Lead,'-'))
FROM    #CheckNULLCOUNT
GROUP   BY LeadId,Lead

DROP TABLE #CheckNULLCOUNT

3 个答案:

答案 0 :(得分:3)

SELECT  Leadid,
        COUNT(Lead) totalNOTNULL,
        SUM(CASE WHEN Lead IS NULL THEN 1 ELSE 0 END) totalNULL
FROM    #CheckNULLCOUNT
GROUP   BY LeadId, [LEAD]

答案 1 :(得分:1)

作为替代解决方案,您可以使用这两个:

SELECT  Leadid,COUNT(Lead)
FROM    #CheckNULLCOUNT
GROUP   BY LeadId, 
     CASE WHEN Lead IS NULL 
        THEN CAST(LeadId AS varchar(8)) 
        ELSE Lead END, Lead

但是因为CAST并不是那么好。我只想添加另外一个想法,GROUP BY本身如何使用CASE...WHEN

答案 2 :(得分:0)

为什么不只是

    SELECT  Leadid,COUNT(*)
    FROM    #CheckNULLCOUNT
    GROUP   BY LeadId,Lead