【问题标题】:BASIC SQL - Case expression - Modifying "Then 1 Else 0" To return count of rows where case statement is trueBASIC SQL - Case 表达式 - 修改“Then 1 Else 0”以返回 case 语句为 true 的行数
【发布时间】:2019-04-19 17:00:13
【问题描述】:

我是一名销售专业人士,有兴趣进一步磨练我的 SQL 技能。到目前为止,Stackoverflow 对我来说是一个很好的资源!

目标:

我想通过 DMA(又名 Metro U.S. Area)获得我们所有客户的不同计数,其中以下案例表达式为真。

问题

现在,当我执行查询时,“当前月份 -1”列的结果计数(应该返回与 case 语句匹配的所有客户的计数)只返回 1。我想要这个返回案例表达式为 true 的 o.intorgnodeID(客户 IDS)的计数(57 个客户)。

换句话说,我怀疑 case 语句的“then 1”部分是导致我出现问题的原因。但我不确定如何修改“1”以仅计算原始案例语句的结果

SELECT
    o.strDMANode --- AKA Metro Market
    ,case when(sum(case when (year(getdate()) - 1) * 12 + month(getdate()) - ((year(sbi.dtmdelivered) - 1) * 12 + month(sbi.dtmdelivered))  = 24 then 1 else 0 end)) >0 then 1 else 0 end as 'Current Month - 1' --- this is the output column that I hope to have return a value of '57'. Currently is returning a '1'
FROM sqlfact.dbo.uvwreport as sbi
    JOIN [sqlDim].[dbo].[uvwdimOrgNodeType1] o ON [sbi].[intDimOrgNodeID] = [o].[intDimOrgNodeID]
    JOIN [sqlDim].[dbo].[uvwdimProductType1] as "z" ON [sbi].[intDimProductPrimaryID] = [z].[intDimProductID]
WHERE 
    ([sbi].[intstatusid] = 5 OR sbi.intsubstatusid = 43) --- Includes only delivered reports
    and [sbi].[mnyDollarcost] > 0 --- NO $0 reports
    and [o].[bitCurrent] = 1 --- Excludes all historical versions of OrgNode, which were duplicates
    and [o].[strSalesRegionNodeGroup]  = 'Construction' 
GROUP BY [o].[strDMANode]
ORDER BY [o].[strDMANode] asc

目前的结果:

strDMANode               Result
ABILENE-SWEETWATER DMA 1               

期望的结果:

strDMANode Column        Result
ABILENE-SWEETWATER DMA   57

【问题讨论】:

    标签: sql count case


    【解决方案1】:

    我认为您希望 case 作为 sum() 的参数:

    sum(case when(case when (year(getdate()) - 1) * 12 + month(getdate()) - ((year(sbi.dtmdelivered) - 1) * 12 + month(sbi.dtmdelivered))  = 24 then 1 else 0 end)) >0 then 1 else 0 end) as 'Current Month - 1'
    

    【讨论】:

    • 好的,所以当我尝试使用该代码字符串时,我收到一条错误消息告诉我:Msg 4145, Level 15, State 1, Line 3 An expression of non-boolean type specified in a context where a condition is expected, near ')'.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-27
    • 2022-01-18
    相关资源
    最近更新 更多