[英]How to arrange the Amount,Debit,Credit and balance in 1 row
我想將我的查詢安排成單行(每個 cdvno、金額、借方、貸方和余額 1 行)但是我無法安排它們。 成1單行
示例代碼
select a.cdvno,b.Amount, a.debit, a.credit, a.credit + a.debit - coalesce(b.amount,0) as balance
from (
select cdvno, debit, sum(credit) credit, trantype
from cdvdtl
where debit = 0
group by cdvno, debit, trantype
union all
select cdvno, sum(debit) debit, credit, trantype
from cdvdtl
where credit = 0
group by cdvno, credit, trantype
) a
left join cdvhdr b
on b.cdvno = a.cdvno
and b.trantype = a.trantype
where a.credit + a.debit - coalesce(b.amount,0) <> 0
order by a.cdvno
結果
cdvno Amount debit credit balance
000-2016-01000004 25137.50 25326.16 0.00 188.66
000-2016-01000004 25137.50 0.00 25326.16 188.66
000-2016-01000005 15849.90 0.00 16010.00 160.10
000-2016-01000005 15849.90 16010.00 0.00 160.10
000-2016-01000007 217938.73 0.00 220006.50 2067.77
000-2016-01000007 217938.73 220006.50 0.00 2067.77
我試過(總和)金額,但它不起作用。 如果可能的話,我希望結果是這樣的
cdvno Amount debit credit balance
000-2016-01000004 25137.5 25326.16 25326.16 188.66
000-2016-01000005 15849.9 16010 16010 160.1
000-2016-01000007 217938.73 220006.5 220006.5 2067.77
非常感謝你們,我知道這對你們來說很簡單,但對我來說,我被困在這里:D newbee
您可以忽略union
(這會導致為借方和credit
創建單獨的條目)並改用select case
。
select a.cdvno,b.Amount
, a.debit
, a.credit
, coalesce(b.amount,0) - coalesce(a.debit, a.credit) as balance
from (
select cdvno
, sum(case when credit = 0 then debit else 0 end) as debit
, sum(case when debit = 0 then credit else 0 end) credit
, trantype
from cdvdtl
group by cdvno, trantype
) a
left join cdvhdr b
on b.cdvno = a.cdvno and b.trantype = a.trantype
where a.credit + a.debit - coalesce(b.amount,0) <> 0
order by a.`cdvno`
我認為你想要聚合條件聚合。 這對我來說很有意義:
select d.cdvno,
sum(case when d.credit = 0 then d.debit end) as debit,
sum(case when d.debit = 0 then d.credit end) as credit,
(h.amount +
sum(case when d.debit = 0 then d.credit end) -
sum(case when d.credit = 0 then d.debit end)
) as balance
from cdvdtl d join
cdvhdr h
on h.cdvno = d.cdvno and h.trantype = d.trantype
group by d.cdvno, h.amount
order by d.cdvno;
注意表別名的使用。 這些不是任意字母,而是表名的縮寫。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.