sql >> Database teknologi >  >> RDS >> Sqlserver

TSQL forskellige tal

Du skal muligvis bruge en midlertidig tabel eller en tabelvariabel som vist nedenfor

     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)

Resultatet er

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


  1. Hvordan fungerer hver række i triggere i mysql?

  2. Sådan indstilles serveroutput til i DataGrip

  3. HTML &PHPMySQL, Indsæt mange data i tabellen fra tekstområdet

  4. MySQL Collation:latin1_swedish_ci Vs utf8_general_ci