使用Union

时间:2016-02-15 21:09:08

标签: mysql

我希望自己只是因为星期一工作日结束而感到难过,而且有人可以帮助我。

基本上我有2个包含发票信息的表和一个包含付款信息的表。使用以下内容,我得到了显示器的第一部分。

SELECT d.id, i.id as invid, i.company_id, d.total, created, adjustment FROM tbl_finance_invoices as i
LEFT JOIN tbl_finance_invoice_details as d ON d.invoice_id = i.id
WHERE company_id = '69350'
UNION
SELECT id, 0, comp_id, amount_paid, uploaded_date, 'paid' FROM tbl_finance_invoice_paid_items
WHERE comp_id = '69350'
ORDER BY created

我想做的是:

创建一个名为" Balance"的新列。无论表的其余部分如何排序,它都会通过创建的列将总计添加到前一个总计。

举一个简单的例子,我当前的输出是这样的:

id | invid | company_id | total | created | adjustment
12 | 16    | 1          | 40    | 01/01/16| 0
100| 0     | 1          | 10    | 01/05/16| 0
50 | 20    | 1          | 50    | 05/01/16| 0

我的目标是:

id | invid | company_id | total | created | adjustment | balance |Notes
12 | 16    | 1          | 40    | 01/01/16| 0          | 40      | 0 + 40
100| 0     | 1          | 10    | 01/05/16| 1          | 50      | 40 + 10
50 | 20    | 1          | 50    | 05/01/16| 0          | 100     | 50 + 50

无论按id,invid,total,created等进行排序,余额总是与创建日期相关联。

所以如果我添加一个" Where调整=' 1'"对我的sql,我会得到:

    100| 0     | 1          | 10    | 01/05/16| 1          | 50      | 40 + 10

1 个答案:

答案 0 :(得分:0)

由于OP在评论中证实了我的理解,我的答案基于以下假设:

  

运行总计将与created_date的顺序相关联。该   运行总计只会受到公司ID作为过滤的影响   标准,所有其他过滤器应该被忽略   计算

由于运行总计可能与查询的其余部分具有不同的顺序和过滤条件,因此必须将运行总计算放在子查询中。

我必须做的另一个假设是,对于单个客户ID,不能有多个发票具有相同的创建日期,因为OP中的原始查询没有任何组或者总和。

我更喜欢在this post on SO中使用@OMG Ponies建议的方法,在那里他在子查询中启动保存运行总计的mysql变量,因此不需要在单独的{{1}中初始化变量声明。

set

如果您还需要考虑SELECT d.id, i.id as invid, i.company_id, rt.total, rt.cumulative_sum, rt.created, adjustment FROM tbl_finance_invoices as i LEFT JOIN tbl_finance_invoice_details as d ON d.invoice_id = i.id LEFT JOIN (SELECT d.total, created, @running_total := @running_total + t.count AS cumulative_sum FROM tbl_finance_invoices as i LEFT JOIN tbl_finance_invoice_details as d ON d.invoice_id = i.id JOIN (SELECT @running_total := 0) r -- no join condition, so this produces a carthesian join WHERE company_id = '69350' ORDER BY created) rt ON i.created=rt.created --this is also an assumption, I do not know which original table holds the created field WHERE company_id = '69350' and adjustment=1 ORDER BY d.id 中的金额,则需要将其添加到子查询中。