【问题标题】:CountDistinct() is counting value twice when grouped in SSRSCountDistinct() 在 SSRS 中分组时计数值两次
【发布时间】:2017-04-19 23:17:33
【问题描述】:
-- Sample data.
declare @Table1 as Table ( RegisterId Int Identity, UnitId Int, DateRegistered date);
declare @Table2 as Table ( Id Int Identity, RegisterId Int, Rep1 int, Rep2 int, DateCreated Date );
declare @Table3 as Table ( UnitId int Identity, UnitName varchar(40), SquadName varchar(40))

insert into @Table1 ( UnitId, DateRegistered ) 
values
  ( 1, '20160115' );
insert into @Table2 ( RegisterId, Rep1, Rep2, DateCreated ) 
values
  ( 1, 3, 4, '20160122' ), ( 1, 10, 4, '20160129' ), ( 1, 32, 45, '20160210' );
insert into @Table3 ( UnitName ) 
values
  ( 'Tango', 'West' ), ( 'Lima', 'West' ), ( 'Foxtrot', 'West' );


SELECT t3.UnitName
       , t2.RegisterId
       , t2.DateCreated
       , t2.Rep1 + t2.Rep2 as 'TotalReps'
       , DateName(month, t2.DateCreated) as 'Month'
       , DateName(year, t2.DateCreated) as 'Year'
FROM @Table1 t1
INNER JOIN @Table2 t2 ON t1.RegisterId = t2.RegisterId
INNER JOIN @Table3 t3 ON t1.UnitId = t3.UnitId

在 SSRS 中构建报告,以上是我的查询。报告参数是开始日期、结束日期和 UnitId。

在报告中,我有 3 个行组 - 月、年、小队名称。在报告中,我将 TotalReps 用于 totalreps,CountDistinct(Field!RegisterId.Value) 用于 ConfirmedRegisters,Count(Field!RegisterId.Value) 用于 CheckIn。 TOTAL 只是表达式的总和,SUM(CountDistinct(Field!RegisterId.Value))。

报告显示如下:

           TotalReps    ConfirmedRegisters  CheckIns
WEST

  2016

    Jan

              21            1            2

    Feb

              77            1            1

TOTAL         98            1            3

一些定义。 ConfirmedRegister 表示 Id 存在于 Table1 AND Table2 中。 Checkin 只是 Table2 Id 的计数。因此,要成为签到,表 2 中必须有一行,并且 ConfirmedREgister 只能被计算一次,无论签到的数量和何时发生。因此,如果 Table1 寄存器发生在 2016 年 1 月,并且如我们的测试数据所示,在 2016 年 1 月和 2 月的 registerid 有签入,则报告应在 2 月的 ConfirmedRegisters 列中显示零,因为 RegisterId 是在 1 月计算的。

应该是:

           TotalReps    ConfirmedRegisters  CheckIns
WEST

  2016

    Jan

              21            1            2

    Feb

              77            0            1

TOTAL         98            1            3

请注意 TOTAL Confirmed Registers 显示正确,我猜是因为它汇总了整个日期范围。但是 CONFIRMEDREGISTERS 列的 MONTHLY 总计不正确,因为它计算的是 1 月和 2 月的 RegisterID,它应该只计算 1 月,而 2 月什么也不填或 0。

不确定我是否需要在查询或报告中解决此问题。

【问题讨论】:

  • 您无法在报告中解决此问题。 CountDistinct 将在它所在的每个组中进行不同的计数。尝试在查询中执行某些操作,就像您怀疑的那样。

标签: sql reporting-services


【解决方案1】:

我通过使用带有窗口函数 (row_number() over(partition ...) 的 CTE 来模拟“First()”类型函数来解决此问题,这样我就可以计算 Table2 中每个 RegisterId 的第一次出现。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多