SQL中的水平UNION ALL

时间:2015-11-25 07:31:33

标签: mysql sql union

基本上我有两张桌子 - 一张填写了付款信息,一张带有付款类型和说明。

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

enter image description here

表2:
frs_PaymentType

enter image description here

我打算做的是查询,以返回每种付款类型的金额总和。换句话说,我的最终结果应该类似于:

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

问题是,如何将两个查询合并为一般情况下可以使用的内容(例如,如果我添加其他付款方式等)

3 个答案:

答案 0 :(得分:0)

使用join

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

答案 1 :(得分:0)

尝试以下

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

答案 2 :(得分:0)

试试这个。这也将采用ptdescription不存在且将返回“未定义”的情况。为了它。

    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