sql >> Base de Datos >  >> RDS >> Sqlserver

Recuentos distintos de TSQL

Es posible que deba usar una tabla temporal o una variable de tabla como se muestra a continuación

     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)

El resultado es

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