【问题标题】:I am getting the issue in SELF JOIN in MYSQL query. Please check the table and query我在 MYSQL 查询中遇到 SELF JOIN 问题。请查表查询
【发布时间】:2018-09-10 16:10:42
【问题描述】:

请通过以下查询创建表:

 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`; 

表格:

错误输出:

此图显示重复数据:

所需输出:

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

说明:

当我们打开交易时,它会存储到交易表中。之后,当我们将关闭交易时,它将以不同的时间和交易量再次输入(如果交易将部分关闭,则交易量将不同,否则完全关闭交易)。 这里第一个条目将 OPEN_TIME 存储为时间,第二个条目将 CLOSE_TIME。那么如何将两个或多个记录转换为具有 OPEN_TIME 和 CLOSE_TIME 的单个记录呢?

【问题讨论】:

  • 我看不到您在哪里计算该 Volume 列。看起来你需要一个带有 COUNT 的 GROUP BY。

标签: mysql self-join


【解决方案1】:

检查一下

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;

【讨论】:

    【解决方案2】:

    将时间条件改为:

    --编辑

    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 成为平仓单实例

    【讨论】:

    • 感谢@codeLover 的回答。但在这里,这种情况不适用于部分关闭的交易。两条以上记录的 positionid 相同时,查看所需的输出和实际表。
    • 请立即检查情况
    • 再次感谢您的回复。但它跳过了订单 42580。
    • 你能看一下你的数据吗,因为如果它适用于其他两个订单,它也应该适用于这个......
    猜你喜欢
    • 2012-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-01
    • 2013-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多