sql >> Database >  >> RDS >> Sqlserver

TSQL verschillende tellingen

Mogelijk moet u een tijdelijke tabel of een tabelvariabele gebruiken, zoals hieronder weergegeven

     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)

Het resultaat is

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


  1. Wat is genoeg opschoning voor een URL?

  2. Wat is een geclusterde indextabel?

  3. Hoe doe je Multiple Inner Joins in Linq to Entities

  4. Postgresql - Database en tabel dynamisch maken