2

我需要根据特定列获取重复记录数。如果字段具有 NULL 值,则它被视为重复。

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
4

3 回答 3

3
SELECT  Leadid,
        COUNT(Lead) totalNOTNULL,
        SUM(CASE WHEN Lead IS NULL THEN 1 ELSE 0 END) totalNULL
FROM    #CheckNULLCOUNT
GROUP   BY LeadId, [LEAD]
于 2013-03-01T15:31:34.947 回答
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

于 2013-03-01T15:42:05.290 回答
0

为什么不只是

    SELECT  Leadid,COUNT(*)
    FROM    #CheckNULLCOUNT
    GROUP   BY LeadId,Lead
于 2013-03-01T16:00:52.503 回答