sql - 将 SQL 查询放在 case 表达式中
问题描述
我想放
SELECT DISTINCT ResidentGroup
FROM Credits.ProductsPurposesBalanceGroups
WHERE BalanceTypeID = 1`
在case
表达式中,因为表Credits.ProductsPurposesBalanceGroups
总是在变化,我需要检查合规性。
当我以这种方式运行下面的代码时,我收到此错误:
无法对包含聚合或子查询的表达式执行聚合函数
如何避免这种情况,或者也许有另一种方法可以做到这一点?
select
p.TypeName as 'Purpose',
sum((case
when tr.CurrencyID = 417
and acc_credit.BalanceGroup in (select distinct ResidentGroup
from Credits.ProductsPurposesBalanceGroups
where BalanceTypeID = 1)
then tr.SumV
else 0
end)) as 'Pay417',
sum((case
when tr.CurrencyID = 840
and acc_credit.BalanceGroup in (select distinct ResidentGroup
from Credits.ProductsPurposesBalanceGroups
where BalanceTypeID = 2)
then tr.SumV
else 0
end)) as 'Pay840',
-- and it goes that way until BalanceTypeID = 16"""
from
dbo.Transactions as tr
inner join
dbo.Accounts as acc_credit on (tr.CreditAccountID = acc_credit.AccountNo)
group by
p.TypeName
order by
p.TypeName
解决方案
一种解决方法是先选择 lineitem,然后在第二遍中聚合。以 CTE 为例:
--Lineitem
;WITH CTE AS (
select
p.TypeName as 'Purpose',
case
when tr.CurrencyID = 417
and acc_credit.BalanceGroup in (select distinct ResidentGroup
from Credits.ProductsPurposesBalanceGroups
where BalanceTypeID = 1)
then tr.SumV
else 0
end as 'Pay417',
case
when tr.CurrencyID = 840
and acc_credit.BalanceGroup in (select distinct ResidentGroup
from Credits.ProductsPurposesBalanceGroups
where BalanceTypeID = 2)
then tr.SumV
else 0
end as 'Pay840'
-- and it goes that way until BalanceTypeID = 16"""
from
dbo.Transactions as tr
inner join
dbo.Accounts as acc_credit on (tr.CreditAccountID = acc_credit.AccountNo)
.
.
.
) --End of CTE
--Aggregate lineitem
SELECT Purpose
,SUM(Pay417) AS [Pay417]
,SUM(Pay840) AS [Pay840]
FROM CTE
group by
Purpose
order by
Purpose
推荐阅读
- java - 如何匹配任何符号,包括行终止符?
- php - SQL error when running command from php file
- python - 从 AWS Python lambda 函数返回 html 页面
- java - JPanel 中的 KeyListener 不接收任何关键事件
- javascript - Mousemove issue [jQuery]
- amazon-web-services - Restrict an IAM policy to run only in an specified account
- javascript - JS,使用 HTML 代替变量
- ios - 我的地面精灵消失了几秒钟,然后又回来了,玩家摔倒了,没有回来
- javascript - React.js 子组件不更新从道具派生的样式,为什么?(样式化组件)
- java - 使用 JSoup 从网站源代码中提取 JavaScript 行