SQL 中的水平 UNION ALL

Horizontal UNION ALL in SQL

基本上我有两个 tables - 一个填充了付款信息,一个填充了付款类型和描述。

Table 1(不是完整的 table,只是第一个条目):
frs_Payment

Table 2:
frs_PaymentType

我想做的是查询 returns 每种付款类型的金额总和。换句话说,我的最终结果应该是这样的:

ptdescription    amountSum
-------------------------
Cash             845.10
Cheque           71.82
Debit            131.67
Credit           203.49

(我已经算出答案了)

获取 ptdescription 很容易:

SELECT ptdescription
FROM frs_PaymentType

获取 amountSum 也是如此:

SELECT SUM(amount) AS amountSum 
FROM frs_Payment
GROUP BY ptid

问题是,我如何将这两个查询组合成我可以在一般情况下使用的东西(即,如果我添加另一种支付类型等)

使用加入

Select ptdescription,SUM(amount) AS amountSum 
From frs_PaymentType t join frs_Payment p
on t.ptid=p.ptid
GROUP BY t.ptid

尝试如下

Select ptdescription, SUM(amount) AS amountSum 
From frs_PaymentType t join frs_Payment p
on t.ptid=p.ptid
GROUP BY ptdescription

试试这个。这也适用于 ptdescription 不存在并且会 return 'Not Defined' 的情况。

    select 
        case when pt.ptdescription is not null 
        then pt.ptdescription
        else 'Not Defined' as ptdescription, 
        sum(p.amount) AS amountSum 
    from frs_Payment p 
       left join frs_PaymentType pt
    on pt.ptid=p.ptid
    GROUP BY pt.ptdescription