join中遇到了这个问题请查表查询

xtfmy6hx  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(285)

请通过以下查询创建表:

CREATE TABLE `trade` 
      ( 
         `order`      VARCHAR(10) DEFAULT NULL, 
         `positionid` INT(11) DEFAULT NULL, 
         `time`       DATETIME DEFAULT NULL, 
         `volume`     FLOAT NOT NULL 
      ) 
    engine=innodb 
    DEFAULT charset=latin1;

插入查询

INSERT INTO `trade` 
                (`order`, 
                 `positionid`, 
                 `time`, 
                 `volume`) 
    VALUES      ('42556', 
                 1111, 
                 '2018-08-15 07:27:44', 
                 2), 
                ('42560', 
                 1111, 
                 '2018-08-18 08:32:47', 
                 2), 
                ('42564', 
                 1235, 
                 '2018-08-21 07:10:12', 
                 5), 
                ('42572', 
                 1235, 
                 '2018-08-23 17:20:26', 
                 2), 
                ('42580', 
                 1235, 
                 '2018-08-23 17:03:30', 
                 3);

我尝试了以下查询:

SELECT b.`order` AS `TICKET`, 
           b.`time`  AS `OPEN_TIME`, 
           j.`time`  AS `CLOSE_TIME` 
    FROM   trade AS b 
           LEFT JOIN trade AS j 
                  ON b.`positionid` = j.`positionid` 
    WHERE  b.`time` != j.`time`;

表格:

错误输出:
此图显示重复数据:

所需输出:
此图将显示所需的输出:

说明:
当我们打开交易时,它将存储到交易表中。之后,当我们结束交易时,它将以不同的时间和数量做另一个条目(如果交易部分结束,那么数量将不同,否则完全结束交易)。第一个条目将打开存储为时间的\u时间,第二个条目将关闭\u时间。那么,如何将两个或多个记录转换为具有打开时间和关闭时间的单个记录呢?

xwbd5t1u

xwbd5t1u1#

看看这个

SELECT j.`order` AS `TICKET`, 
b.`positionid` AS `PositionID`,
   b.`time`  AS `OPEN_TIME`, 
   j.`time`  AS `CLOSE_TIME` ,
   j.`volume` AS `Volume`
FROM   trade AS b 
   INNER JOIN trade AS j 
          ON b.`positionid` = j.`positionid` 
where b.time = (select min(time) from trade as c1 where b.positionid=c1.positionid)
AND b.time!=j.time;
qco9c6ql

qco9c6ql2#

将时间条件更改为:
--编辑

where j.time = (select max(time) from test_query where positionid = j.positionid) 
and b.time = (select min(time) from test_query where positionid = b.positionid)

以便 b 示例对于打开的订单和 j 成为关闭订单的示例

相关问题