根据其他2列的条件填充列

时间:2019-12-09 07:13:41

标签: mysql

我有一种情况需要

打印“相同”-

  

2列为空或

     

均为空或

     

重复相同的模式

打印“上”-如果

  

COL2大于COL1(仅在这一点上,如果它在随后的行中继续相同的模式,则应仅打印如上所述的“ SAME”)

打印“ DOWN”-如果

  

COL1大于COL2(仅在这一点上,如果它在随后的行中继续相同的模式,则应仅打印如上所述的“ SAME”)

例如

DATE         **COL1  COL2    RESULT**
2019-01-01      0             SAME
2019-01-02      1     2       **UP**
2019-01-03      2     3       SAME
2019-01-04      3     4       SAME
2019-01-05      4     1       **DOWN**
2019-01-06      5     2       SAME
2019-01-07      6     3       SAME
2019-01-08      7     7       SAME
2019-01-09      8             SAME
2019-01-10      9     8       SAME
2019-01-11                    SAME
2019-01-12            4       SAME
2019-01-13      7     8       **UP**    

1 个答案:

答案 0 :(得分:1)

此解决方案的开始有些人为的设计,但也许有人可以考虑如何消除这些麻烦。另外,由于我这样做的方式有点怪癖,因此此解决方案仅适用于8.0之前的版本...

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(DATE DATE PRIMARY KEY
,COL1 INT NULL
,COL2 INT NULL
);

INSERT INTO my_table VALUES
('2019-01-01',0,NULL),
('2019-01-02',1,2),
('2019-01-03',2,3),
('2019-01-04',3,4),
('2019-01-05',4,1),
('2019-01-06',5,2),
('2019-01-07',6,3),
('2019-01-08',7,7),
('2019-01-09',8,NULL),
('2019-01-10',9,8),
('2019-01-11',NULL,NULL),
('2019-01-12',NULL,4),
('2019-01-13',7,8);  

SELECT date, x result FROM
     ( SELECT date
     , CASE WHEN @p = result THEN @i:= 'same' ELSE @i:=result END x
     , @p:= result
  FROM 
     ( SELECT date
            , @prev := CASE WHEN col1 > col2 THEN 'down' WHEN col1 < col2 THEN 'up' ELSE @prev END result
         FROM my_table
            , (SELECT @prev:='same') vars -- this is the contrived part
        ORDER
           BY date
     ) n
     , (SELECT @p:=null,@i:=null) more_vars 
 ORDER
    BY date
    ) b
 ORDER BY date;
  +------------+--------+
  | date       | result |
  +------------+--------+
  | 2019-01-01 | same   |
  | 2019-01-02 | up     |
  | 2019-01-03 | same   |
  | 2019-01-04 | same   |
  | 2019-01-05 | down   |
  | 2019-01-06 | same   |
  | 2019-01-07 | same   |
  | 2019-01-08 | same   |
  | 2019-01-09 | same   |
  | 2019-01-10 | same   |
  | 2019-01-11 | same   |
  | 2019-01-12 | same   |
  | 2019-01-13 | up     |
  +------------+--------+