MySQL垂直水平和和垂直和同时

时间:2016-04-21 03:52:58

标签: mysql

我有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

3 个答案:

答案 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;

SQL FIDDLE DEMO

注意:

如果您使用@prevBalance初始化zero变量,则不再需要IFNULL(@prevBalance,0)

所以,如果你使用它:

(SELECT @prevBalance := 0) var

然后更改平衡栏,如下所示:

@prevBalance := (t.in_qty - t.out_qty) + @prevBalance