TSQL Distinct Counts

℡╲_俬逩灬. 提交于 2019-12-12 06:22:36

问题


I have a table that looks like this:

ID SuppressionTypeID PersonID
------------------------------
1  1                 123
2  1                 456
3  2                 456

I want to get a rolling count (distinct people) rather than a normal group by count.

e.g. not this:

SuppressionTypeID    Count
---------------------------
1                    2
2                    1

This:

SuppressionTypeID    RecordsLost
----------------------------------
1                    2
2                    0

The latter being zero as we lost person 456 on suppresiontypeid 1.

Thanks in advance.


回答1:


You may need to use a temporary table or a table variable as shown below

     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)

The result is

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



回答2:


You can try;

with tmp_tbl as (
  select 
    x.SuppressionTypeID, count(x.PersonID) as RecordsLost
  from (
    select 
      min(SuppressionTypeID) as SuppressionTypeID,
      PersonID
    from tbl
    group by PersonID
  ) as x
  group by x.PersonID
  order by x.SuppressionTypeID
)
select 
  distict t.SuppressionTypeID, coalesce(tmp.RecordsLost, 0) as RecordsLost
from tbl t
left join tmp_tbl tmp on tmp.SuppressionTypeID = t.SuppressionTypeID


来源:https://stackoverflow.com/questions/31874550/tsql-distinct-counts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!