TSQL Distinct Counts

时间:2015-08-07 09:40:13

标签: sql sql-server-2012

我有一个看起来像这样的表:

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

我希望按计数获得滚动计数(不同的人)而不是正常组。

e.g。不是这个:

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

此:

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

后者为零,因为我们在suppresiontypeid 1上丢失了人456。

提前致谢。

2 个答案:

答案 0 :(得分:0)

你可以试试;

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

答案 1 :(得分:0)

您可能需要使用临时表或表变量,如下所示

     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)

结果是

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