比较两行

时间:2014-12-21 08:10:16

标签: mysql sql rows

我希望查询能够在新的/后续的“关闭”结束时高于之前的高(当你看到日期逐渐向底部增长时)时给出结果ID。

ID | Date        | Open | High | Low  | Close
---------------------------------------------
1  | 01.01.2014  | 20   | 22   | 19  |  21 
2  | 02.01.2014  | 21   | 23   | 20  |  23       (this Close is higher than previous High)
3  | 03.01.2014  | 23   | 26   | 18  |  19
4  | 04.01.2014  | 19   | 24   | 18  |  24

例如,对于上述股票价格,结果将返回:“2”,因为ID_2的“收盘价”高于“ID_1的高点”。

我正在摆弄SELF-JOIN,但无法让它发挥作用。非常欣赏指向正确方向的指针。

1 个答案:

答案 0 :(得分:-5)

你去吧

DDL

create table shares
(
  id int,
  date_d date,
  open int,
  high int,
  low int,
  close int
  );


insert into shares (id,  date_d,  open,  high,  low,  close)
values 
(1,'01-JAN-2014',20,22,19,21);

insert into shares (id,  date_d,  open,  high,  low,  close)
values 
(2,'02-JAN-2014',21,23,20,23);
insert into shares (id,  date_d,  open,  high,  low,  close)
values 
(3,'03-JAN-2014',23,26,18,19);
insert into shares (id,  date_d,  open,  high,  low,  close)
values 
(4,'04-JAN-2014',19,24,18,24);

你的SQL

select ID,S.DATE_D,OPEN,HIGH,LOW,CLOSE FROM SHARES S
WHERE CLOSE > (SELECT HIGH FROM SHARES WHERE DATE_D = S.DATE_D-1)

你甚至可以看到这个SQL中的前一个高点

select ID,S.DATE_D,OPEN,HIGH,LOW,CLOSE, (SELECT HIGH FROM SHARES WHERE DATE_D = S.DATE_D-1) as prev_high FROM SHARES S
WHERE CLOSE > (SELECT HIGH FROM SHARES WHERE DATE_D = S.DATE_D-1)

http://sqlfiddle.com/#!4/6b08a/12