如何编写查询以获取输出,如下所示在我的sql中

时间:2013-10-28 07:10:16

标签: mysql

帐单表

Bill_date   Total
28/10/13    10000
27/10/13    5000

付款表

Paid_on    amount
28/10/13   5000
30/10/13   10000

预期输出

date        Credit    debit
27/10/13    5000    
28/10/13    10000     5000
30/10/13              10000

5 个答案:

答案 0 :(得分:1)

select b.bill_date, sum(b.total), sum(p.amount)
from bills b full outer join payments p on b.bill_date=p.paid_on
group by b.bill_date
order by b.bill_date

您需要完整的外部联接来获取包含账单但没有付款的天数以及有付款但没有账单的天数。

答案 1 :(得分:1)

试试这个

SELECT t1.bill_date, t1.total as Credit, t2.total as debit  FROM Bills t1
LEFT JOIN Payments t2 ON t1.bill_date= t2.bill_date
UNION
SELECT t2.bill_date, t1.total as Credit, t2.total as debit FROM Bills t1
RIGHT JOIN Payments t2 ON t1.bill_date= t2.bill_date

答案 2 :(得分:0)

SELECT t1.bill_date as `date`, t1.Total as Credit, t2.amount as debit  FROM Bills t1
LEFT JOIN Payments t2 ON t1.bill_date= t2.Paid_on
UNION
SELECT t2.Paid_on as `date`, t1.Total as Credit, t2.amount as debit FROM Bills t1
Right JOIN Payments t2 ON t1.bill_date <> t2.Paid_on
UNION
SELECT t1.bill_date as `date`, t1.Total as Credit, t2.amount as debit  FROM Bills t1
LEFT JOIN Payments t2 ON t1.bill_date <> t2.Paid_on

答案 3 :(得分:0)

查询应该像,

SELECT t1.bill_date, t1.total AS Credit, t2.amount AS debit
FROM Bills t1
LEFT JOIN Payments t2 ON t1.bill_date = t2.paid_on
UNION
SELECT t2.paid_on, t1.total AS Credit, t2.amount AS debit
FROM Bills t1
RIGHT JOIN Payments t2 ON t1.bill_date = t2.paid_on

答案 4 :(得分:-2)

您可以尝试使用此代码。

  SELECT concat(`Bill_date`,' ',`Total`) FROM `tblname`