BASIC SQL - 案例表达式 - 修改“Then 1 Else 0”返回case语句为true的行数

问题描述 投票:-1回答:1

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

目标:

我想通过DMA(又名Metro美国地区)获得所有客户的明显统计数据,其中下面的案例表达式为真。

问题

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

换句话说,我怀疑案例陈述中的“然后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个回答
0
投票

我想你想要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'
© www.soinside.com 2019 - 2024. All rights reserved.