简体   繁体   English

T-SQL查询不会为总和返回0值

[英]T-SQL Query will not return 0 value for a Sum

I have a query where I'm calculating Days of Therapy for medications. 我有一个查询,正在计算药物的治疗天数。 I want to have 0 values to show for months that have no data. 我希望有0个值来显示没有数据的月份。 Currently the query returns no record if the Sum is 0. Can't seem to figure this out. 当前,如果Sum为0,查询将不返回任何记录。似乎无法弄清楚。 See the Query Below: 请参阅下面的查询:

If I were to comment out identifiers related to the DOT_ALL table along with the Where Clause I get 60 rows, 1 for each month for the past 5 years. 如果我要注释掉与DOT_ALL表相关的标识符以及Where子句,我将获得60行,过去5年中,每个月1行。 However, otherwise i get only 57 for the drug in the Where Clause since there are not DOTs for Aug 2016, April 2016 and Jan 2015. 但是,在其他情况下,由于在2016年8月,2016年4月和2015年1月没有DOT,因此我在Where子句中只能获得57种药物。

Thanks in advance. 提前致谢。

----------------------------------------------------------------------------

SELECT
    AMS.[Medication Name]
    , SUM(AMS.DOT) AS DOT
    ,  PD.[Patient Days]
    , PD.[Month_Name]
    , PD.[Fiscal_Month]
    , PD.[Accounting_Year]
    , PD.[Year]

FROM
    DW_PROD.dbo.Patient_Days_By_Month PD 
    Left JOIN [DW_PROD].[dbo].[DOTS_All] AMS ON (PD.Month_Name = AMS.Month AND PD.Year = AMS.Year)

WHERE
    [Medication Name] = 'CEFUROXIME'

GROUP BY
    AMS.[Medication Name]
    , PD.[Patient Days]
    , PD.[Month_Name]
    , PD.[Fiscal_Month]
    , PD.[Accounting_Year]
    , PD.[Year]

ORDER BY
    ACCOUNTING_YEAR
    ,FISCAL_MONTH

This may be the cheapest solution, under the assumption that Patient_Days_By_Month is already some kind of calendar. 假设Patient_Days_By_Month已经是某种日历,这可能是最便宜的解决方案。

SELECT
    'CEFUROXIME' AS [Medication Name],
    SUM(AMS.DOT) AS DOT,
    PD.[Patient Days],
    PD.[Month_Name],
    PD.[Fiscal_Month],
    PD.[Accounting_Year],
    PD.[Year]
FROM DW_PROD.dbo.Patient_Days_By_Month PD 
LEFT JOIN [DW_PROD].[dbo].[DOTS_All] AMS 
    ON PD.Month_Name = AMS.Month 
    AND PD.Year = AMS.Year
    AND [Medication Name] = 'CEFUROXIME'
GROUP BY
    PD.[Patient Days],
    PD.[Month_Name],
    PD.[Fiscal_Month],
    PD.[Accounting_Year],
    PD.[Year]
ORDER BY
    PD.ACCOUNTING_YEAR,
    PD.FISCAL_MONTH

JOIN conditions do not need to refer to columns in other tables, they can as well contain constants . JOIN条件不需要引用其他表中的列,它们还可以包含常量

The medication name was originally restricted in the WHERE clause - that eliminated all non-cefuroxime records from the resultset. 药物名称最初在WHERE子句中受到限制-从结果集中删除了所有非头孢呋辛记录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM