我有一个脚本可以从数据库中提取事务及其详细信息。但是我的用户抱怨生成的文件大小太大,因此他们要求某些交易只是总结/合并而不是它们具有某种分类,比如检查帐户。这意味着结果集中只应该有一行名为“Checking”,其中包含Checking Accounts下所有交易的总和。有没有办法使SQL脚本像:
CASE
WHEN Acct_class = 'Checking'
then sum(tran_amount)
ELSE tran_amount
END
我已经有了正确的GROUP BY
和ORDER BY
语句,但我似乎无法得到我想要的输出。结果集中仍有多个“正在检查”行。任何想法都会非常感激。
答案 0 :(得分:0)
试试这个,
Select sum(tran_amount) From tran_amount Where Acct_class = 'Checking'
答案 1 :(得分:0)
您可以尝试使用the git-log
documentation
SELECT tran_amount, .... FROM table WHERE NOT Acct_class = 'Checking'
UNION ALL
SELECT SUM(tran_amount), .... FROM table WHERE Acct_class = 'Checking' GROUP BY Acct_class, ...;
答案 2 :(得分:0)
您可以尝试以下内容,为某些类保留单行,并为其他类聚合:
with test (id, class, amount) as
(
select 1, 'a' , 100 from dual union all
select 2, 'a' , 100 from dual union all
select 3, 'Checking', 100 from dual union all
select 4, 'Checking', 100 from dual union all
select 5, 'c' , 100 from dual union all
select 6, 'c' , 100 from dual union all
select 7, 'c' , 100 from dual union all
select 8, 'd' , 100 from dual
)
select sum(amount), class
from test
group by case
when class = 'Checking' then null /* aggregates elements of class 'b' */
else id /* keeps elements of other classes not aggregated */
end,
class
答案 3 :(得分:0)
嗨,你可以尝试下面的sql
select account_class,
case when account_class = 'saving' then listagg(trans_detail, ',') within group (order by emp_name) -- will give you all details transactions
when account_class = 'checking' then to_char(sum(trans_detail)) -- will give you only sum of transactions
end as trans_det from emp group by account_class;
答案 4 :(得分:0)
或者,如果您想要的输出得到总和,或者基于另一个列值的实际列值,解决方案是使用分析函数将总和与实际值一起得到:
select
decode(acct_class, 'Checking', tran_amount_sum, tran_amount)
from (
select
sum(tran_amount) over (partition by acct_class) as tran_amount_sum,
tran_amount,
acct_class
from
YOUR_TABLE
)