10. 小さい方は出ないようにしよう。
select
case
when 借方合計 > 貸方合計 then (借方合計 - 貸方合計)
else null
end as 借方残高,
勘定科目名,
case
when 借方合計 < 貸方合計 then (貸方合計 - 借方合計)
else null
end as 貸方残高
from 合計試算表
16. 両方繋ぐと?
select 借方.借方合計, 借方.勘定科目名, 貸方.貸方合計
from (
select 勘定科目名, sum(金額) as 借方合計
from 仕訳帳
where 貸借 = '借方'
group by 勘定科目名
) as 借方
inner join (
select 勘定科目名, sum(金額) as 貸方合計
from 仕訳帳
where 貸借 = '貸方'
group by 勘定科目名
) as 貸方
on 貸方.勘定科目名 = 借方.勘定科目名
18. left outerだと?
select 借方.借方合計, 借方.勘定科目名, 貸方.貸方合計
from (
select 勘定科目名, sum(金額) as 借方合計
from 仕訳帳
where 貸借 = '借方'
group by 勘定科目名
) as 借方
left outer join (
select 勘定科目名, sum(金額) as 貸方合計
from 仕訳帳
where 貸借 = '貸方'
group by 勘定科目名
) as 貸方
on 貸方.勘定科目名 = 借方.勘定科目名
20. full outerだと?
select 借方.借方合計, 借方.勘定科目名, 貸方.貸方合計
from (
select 勘定科目名, sum(金額) as 借方合計
from 仕訳帳
where 貸借 = '借方'
group by 勘定科目名
) as 借方
full outer join (
select 勘定科目名, sum(金額) as 貸方合計
from 仕訳帳
where 貸借 = '貸方'
group by 勘定科目名
) as 貸方
on 貸方.勘定科目名 = 借方.勘定科目名
22. 最終的に、こんな感じ。
select 借方.借方合計, coalesce(借方.勘定科目名, 貸方.勘定科目名) as 勘定科目名, 貸方.貸方合計
from (
select 勘定科目名, sum(金額) as 借方合計
from 仕訳帳
where 貸借 = '借方'
group by 勘定科目名
) as 借方
full outer join (
select 勘定科目名, sum(金額) as 貸方合計
from 仕訳帳
where 貸借 = '貸方'
group by 勘定科目名
) as 貸方
on 貸方.勘定科目名 = 借方.勘定科目名
25. ということで、別解。
select
sum(case when 貸借 = '借方' then 金額 else 0 end) as 借方合計,
勘定科目名,
sum(case when 貸借 = '貸方' then 金額 else 0 end) as 貸方合計
from 仕訳帳
group by 勘定科目名
26. 最終的に合計残高試算表は
select
case when 借方合計 > 貸方合計 then (借方合計 - 貸方合計) else null end as 借方残高,
借方合計,
勘定科目名,
貸方合計,
case when 借方合計 < 貸方合計 then (貸方合計 - 借方合計) else null end as 貸方残高
from (
select
sum(case when 貸借 = '借方' then 金額 else 0 end) as 借方合計,
勘定科目名,
sum(case when 貸借 = '貸方' then 金額 else 0 end) as 貸方合計
from 仕訳帳
group by 勘定科目名
) as 合計試算表