我已经回顾了其他类似的问题,但我的查询中没有Where
条款,这让我对如何解决它感到困惑。
INSERT INTO #tmpCombined
SELECT A.Region
, 'MyLocation' AS 'Location'
, c.Id AS 'CompID'
, c.Name AS 'CompName'
, 'Cash' AS 'Context'
, isnull( sum( CASE WHEN T.TranAge >= 0 and CASE WHEN T.TranAge < 1 THEN 1 ELSE 0 END,0 )) AS 'ZeroDays0'
, isnull( sum( CASE WHEN T.TranAge >= 1 and CASE WHEN T.TranAge < 8 THEN 1 ELSE 0 END ), 0 ) AS '1to7Days'
, isnull( sum( CASE WHEN T.TranAge >= 8 and CASE WHEN T.TranAge < 16 THEN 1 ELSE 0 END ), 0 ) AS '8to15Days'
, isnull( sum( CASE WHEN T.TranAge >= 16 and CASE WHEN T.TranAge < 20 THEN 1 ELSE 0 END ), 0 ) AS '16to20Days'
, isnull( sum( CASE WHEN T.TranAge >= 20 THEN 1 ELSE 0 END ), 0 ) AS '20DaysPlus'
, COUNT(1) AS 'Total'
, A.Level as 'Level'
, sum(T.USDDifference) AS 'USDRevaluation'
from MyLocation.dbo.Company C
inner join #tmpCashTBResults T on T.CompanyId = C.Id
inner join #tmpCashAccounts A on T.CompanyId = A.CompanyId
group by A.Region, C.Id, C.Name, A.Level
答案 0 :(得分:1)
T.TranAge&gt; = 0时的情况和T.TranAge&lt;时的情况1那么1
这应该是
CASE
WHEN T.TranAge >= 0 and T.TranAge < 1 THEN 1
...
这是使用CASE ... WHEN构造指定复合条件的语法。
答案 1 :(得分:0)
这一点:
THEN 1 ELSE 0 END,0 )) AS 'ZeroDays0'
应该是
THEN 1 ELSE 0 END) ,0 ) AS 'ZeroDays0'
也许?
答案 2 :(得分:0)
你在,0
错误的地方,改变这个:
isnull( sum( CASE WHEN T.TranAge >= 0 and CASE WHEN T.TranAge < 1 THEN 1 ELSE 0 END,0 ))
为:
isnull( sum( CASE WHEN T.TranAge >= 0 and CASE WHEN T.TranAge < 1 THEN 1 ELSE 0 END), 0)
此外,您的case
语句错误,条件中不应该有另一个case
。改变那些看起来像这样的人;
CASE WHEN T.TranAge >= 0 and CASE WHEN T.TranAge < 1 THEN 1 ELSE 0 END
为:
CASE WHEN T.TranAge >= 0 and T.TranAge < 1 THEN 1 ELSE 0 END
答案 3 :(得分:0)
请对您的案件情况进行更改:
, isnull( sum( CASE WHEN T.TranAge >= 0 and T.TranAge < 1 THEN 1 ELSE 0 END ),0) AS 'ZeroDays0'
答案 4 :(得分:0)
对于ZeroDays0列,您传递,0
作为SUM函数的参数,而不是ISNULL。
答案 5 :(得分:0)
您的查询中要解决的问题
SUM(CASE.. WHEN.. THEN 1 ELSE 0 END)
时,CASE语句的本质是它永远不会为NULL,因此用ISNULL包装它是多余的。CASE
的基本结构是CASE WHEN <condition> THEN <value>
。这里的<condition>
可以是任何表达式,甚至是多重比较。更正并重新格式化的查询:
INSERT INTO #tmpCombined
SELECT A.Region
, 'MyLocation' AS Location
, c.Id AS CompID
, c.Name AS CompName
, 'Cash' AS Context
, sum( CASE WHEN T.TranAge >= 0 and T.TranAge < 1 THEN 1 ELSE 0 END) AS ZeroDays0
, sum( CASE WHEN T.TranAge >= 1 and T.TranAge < 8 THEN 1 ELSE 0 END) AS [1to7Days]
, sum( CASE WHEN T.TranAge >= 8 and T.TranAge < 16 THEN 1 ELSE 0 END) AS [8to15Days]
, sum( CASE WHEN T.TranAge >= 16 and T.TranAge < 20 THEN 1 ELSE 0 END) AS [16to20Days]
, sum( CASE WHEN T.TranAge >= 20 THEN 1 ELSE 0 END) AS [20DaysPlus]
, COUNT(1) AS Total
, A.Level as Level
, sum(T.USDDifference) AS USDRevaluation
from MyLocation.dbo.Company C
join #tmpCashTBResults T on T.CompanyId = C.Id
join #tmpCashAccounts A on T.CompanyId = A.CompanyId
group by A.Region, C.Id, C.Name, A.Level;