我有2个表,其中包含一组数据,如下所示,我想得到结果,结果将在字段balance
中进行计算:
我被卡在balance
字段上,如何让balance
运行?
tblIn
in_date | code | in_qty
-----------|---------|---------
2016-04-01 | aaa | 100
2016-04-03 | aaa | 200
2016-04-06 | aaa | 400
tblOut
out_date | code | out_qty
-----------|---------|---------
2016-04-02 | aaa | 100
2016-04-08 | aaa | 400
RESULT
date | code | in_qty | out_qty | balance
-----------|---------|----------|----------|---------
2016-04-01 | aaa | 100 | 0 | 100
2016-04-02 | aaa | 0 | 100 | 0
2016-04-03 | aaa | 200 | 0 | 200
2016-04-06 | aaa | 400 | 0 | 600
2016-04-08 | aaa | 0 | 400 | 200
QUERY
SELECT
t.date,
t. CODE,
t.in_qty,
t.out_qty
FROM
(
SELECT
date,
in_qty,
0 AS out_qty
FROM tblIn
UNION ALL
SELECT
date,
0 AS in_qty,
out_qty
FROM tblOut
) t
ORDER BY date ASC
答案 0 :(得分:1)
嗯,让我们这样做;)
CREATE TABLE IF NOT EXISTS `tblIn` (
`in_date` date DEFAULT NULL,
`code` char(50) DEFAULT NULL,
`in_qty` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `tblOut` (
`out_date` date DEFAULT NULL,
`code` char(50) DEFAULT NULL,
`out_qty` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
然后尝试这个,也许可以工作;)
SELECT TMP.date, TMP.code, TMP.in_qty, TMP.out_qty, @BALANCE:=@BALANCE + TMP.BALANCE AS balance
FROM (
SELECT out_date as date,
code,
0 as in_qty,
out_qty,
0-out_qty as balance
FROM tblOut
UNION
SELECT in_date as date,
code,
in_qty,
0 as out_qty,
in_qty as balance
FROM tblIn) TMP,
(SELECT @BALANCE:=0) B
ORDER BY TMP.date
答案 1 :(得分:0)
通常使用带有日期的完全外连接作为公共因子,但MySQL不允许完全外连接。
下面的链接有一个解决方法
http://www.xaprb.com/blog/2006/05/26/how-to-write-full-outer-join-in-mysql/
在ON条件中指定日期。
答案 2 :(得分:0)
您可以尝试此查询:
SELECT
t.*,
@prevBalance := (t.in_qty - t.out_qty) + IFNULL(@prevBalance,0) AS balance
FROM
(
SELECT
in_date date,
code,
in_qty,
0 AS out_qty
FROM tblin
UNION
SELECT
out_date,
code,
0,
out_qty
FROM tblout
) t , (SELECT @prevBalance := NULL) var
ORDER BY t.date;
注意:强>
如果您使用@prevBalance
初始化zero
变量,则不再需要IFNULL(@prevBalance,0)
。
所以,如果你使用它:
(SELECT @prevBalance := 0) var
然后更改平衡栏,如下所示:
@prevBalance := (t.in_qty - t.out_qty) + @prevBalance