CASE WHEN时的计算

时间:2019-04-17 09:25:07

标签: sql sql-server sql-server-2008

我正在使用SQL Server 2008,正在尝试在when语句的情况下进行一些计算。

我在[PM]的最后一栏中有问题,在使用date参数@StartDate@EndDate的情况下,是否有其他建议可以在案例中进行计算?

DECLARE @StartDate date = '1/1/2019'
DECLARE @EndDate date = '4/30/2019'
DECLARE @StartDatePreviousYear date = DATEADD(YEAR, -1, @StartDate)
DECLARE @EndDatePreviousYear date = DATEADD(YEAR, -1, @EndDate)

SELECT
     DATENAME(month, [GL_DATEPIECE]) AS [MONTH]
    ,[et_region] AS [REGION]
    ,[e].[et_etablissement] AS [STORE CODE]
    ,[et_libelle] AS [STORE NAME]
    ,SUM(CASE WHEN [GP_DATEPIECE] BETWEEN @StartDate AND @EndDate THEN ISNULL([gl_totalttcdev], 0) ELSE 0 END) AS [CA]
    ,SUM(CASE WHEN [GP_DATEPIECE] BETWEEN @StartDatePreviousYear AND @EndDatePreviousYear THEN ISNULL([gl_totalttcdev], 0) ELSE 0 END) AS [CA_AN],
(CASE WHEN [GP_DATEPIECE] BETWEEN @StartDate AND @EndDate THEN ISNULL(sum(gl_totalttcdev)/count(distinct(GL_NUMERO)), 0) ELSE 0 END) AS [PM]

FROM [piece]
    LEFT OUTER JOIN [etabliss] AS [e] ON [piece].[gp_etablissement] = [e].[et_etablissement]
GROUP BY
     DATENAME(month, [GL_DATEPIECE])
    ,[et_region]
    ,[et_etablissement]
    ,[et_libelle]
ORDER BY
     [et_region] ASC
    ,[et_etablissement] ASC

2 个答案:

答案 0 :(得分:0)

如果您的GP_DATEPIECE列是日期时间,则您的“大小写”应该正确。但是你不能除以零,不要忘记它。

尝试类似的东西:

CASE 
WHEN count(distinct(GL_NUMERO)=0 then 0
WHEN [GP_DATEPIECE] BETWEEN @StartDate AND @EndDate THEN ISNULL(sum(gl_totalttcdev)/count(distinct(GL_NUMERO)), 0) ELSE 0 
END AS [PM]

答案 1 :(得分:0)

使用models

NULLIF