Sqlserver
 sql >> Base de données >  >> RDS >> Sqlserver

Comptes distincts TSQL

Vous devrez peut-être utiliser une table temporaire ou une variable de table comme indiqué ci-dessous

     DECLARE @t TABLE (
    ID INT
    ,SuppressionTypeID INT
    ,PersonID INT
    )

INSERT INTO @t
SELECT 1
    ,1
    ,123

UNION ALL

SELECT 2
    ,1
    ,456

UNION ALL

SELECT 3
    ,2
    ,456

DECLARE @t1 TABLE (
    ID INT
    ,SuppressionTypeID INT
    ,PersonID INT
    ,firstid INT
    )

INSERT INTO @t1
SELECT *
    ,NULL
FROM @t

UPDATE t1
SET t1.firstid = t2.firstid
FROM @t1 AS t1
INNER JOIN (
    SELECT personid
        ,min(SuppressionTypeID) AS firstid
    FROM @t1
    GROUP BY personid
    ) AS t2 ON t1.PersonID = t2.PersonID

SELECT coalesce(t2.firstid, t1.SuppressionTypeID) AS SuppressionTypeID
    ,count(DISTINCT t2.personid) AS count
FROM @t1 AS t1
LEFT JOIN @t1 AS t2 ON t1.personid = t2.personid
    AND t1.SuppressionTypeID = t2.firstid
GROUP BY coalesce(t2.firstid, t1.SuppressionTypeID)

Le résultat est

SuppressionTypeID count
----------------- -----------
1                 2
2                 0