0

我有以下代码:

     SELECT 
            ehrprg.ReportName 
           ,ehrprg.AnnualGoalServiceMinutes
           ,COUNT(DISTINCT ct.[ClientFK]) AS [UnduplicatedClients]

    FROM 
           [WH].[Fact].[EHRClinicalTransaction] ct
    INNER JOIN [Dimension].EHRProgram ehrprg ON 
                           ct.ProgramFK = ehrprg.WHID

    WHERE
          ehrprg.AnnualGoalServiceMinutes > 0

    GROUP BY
            ehrprg.ReportName 
           ,ehrprg.AnnualGoalServiceMinutes 

    ORDER BY
           ReportName 

结果:

在此处输入图像描述

但我需要它在[ReportName]列中只有一个“SM NV”(而不是 2)和一个“SM REACH”(而不是 3)行,总结[ServiceMinutes]

当我使用SUM(ehrprg.AnnualGoalServiceMinutes)时,它给了我“转换为数据类型 int 的算术溢出错误”错误。

然后,我尝试了SUM(CONVERT(BIGINT, ehrprg.AnnualGoalServiceMinutes)),但得到以下结果:

在此处输入图像描述

它仍然没有分组(没有总结AnnualGoalServiceMinutes)并给出了一些值,我无法理解

我的目标是看到而不是——

        ReportName   AnnualGoalServiceMin
        SM NV        197885
        SM NV        348654

        SM REACH     40000 
        SM REACH     80000
        SM REACH     380000

我期望 AnnualGoalServiceMin 的总和:

       ReportName   AnnualGoalServiceMin
       SM NV        546539
       SN REACH     500000           

请帮忙

4

1 回答 1

0

我不知道溢出错误的来源(它不应该基于所涉及的整数的大小而发生),但我认为您需要的是第二级聚合:

WITH cte AS (
    SELECT
        ehrprg.ReportName,
        ehrprg.AnnualGoalServiceMinutes,
        COUNT(DISTINCT ct.[ClientFK]) AS UnduplicatedClients
   FROM [WH].[Fact].[EHRClinicalTransaction] ct
   INNER JOIN [Dimension].EHRProgram ehrprg
        ON ct.ProgramFK = ehrprg.WHID
   WHERE ehrprg.AnnualGoalServiceMinutes > 0
   GROUP BY ehrprg.ReportName, ehrprg.AnnualGoalServiceMinutes
)

SELECT
    ReportName,
    SUM(AnnualGoalServiceMinutes) AS AnnualGoalServiceMinutes,
    SUM(UnduplicatedClients) AS UnduplicatedClients
FROM cte
GROUP BY
    ReportName;
于 2019-05-02T05:41:59.490 回答