How to use Group By and self-join to return min, max, open, and close daily price restult set?

前端 未结 2 847
广开言路
广开言路 2021-01-15 17:39

SOLVED

All hail StackOverlow!

While I was gone, people left 2 solutions (thanks guys--what is the protocol for handing out karma for two wor

2条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-15 18:17

    SELECT
      a.trading_day, a.min_price, a.max_price, 
      b.price as opn_price, 
      c.price as cls_price
    FROM
      (SELECT 
         DATE_FORMAT(`DTE`, "%m/%d/%Y") AS trading_day,
         MIN(`PRICE`) AS min_price,
         MAX(`PRICE`) AS max_price,
         MIN(`dte`) AS open_date,
         MAX(`dte`) AS close_date
       FROM `CHART_DATA`
       GROUP BY trading_day) a
    LEFT JOIN
      `CHART_DATA` b ON b.dte = a.open_date
    LEFT JOIN
      `CHART_DATA` c ON c.dte = a.close_date
    

    Note: this solution may present some problems if your opening or closing entry has the exact same date/time value as another row (i.e. the transaction that came immediately after opening, or immediately before closing). To address this, I would suggest that you add a sequence number that is stored in a way that guarantees uniqueness, and increasing-with-respect-to-time. If you do this, then you would use the sequence value in the place of dte to replace the open_date and close_date I've used as join fields in my example.

提交回复
热议问题