Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>So you want:</p> <ul> <li>The alias <code>C</code> to correspond to all rows in the group for a given day, so you can use <code>MAX()</code> and <code>MIN()</code> over the rows in that group.</li> <li>The alias <code>C2</code> to correspond to the last row in a given day.</li> <li>The alias <code>C3</code> to correspond to a row later than <code>C2</code> on the same day. If none is found, i.e. <code>C3.*</code> is NULL, then <code>C2</code> is the latest on that day.</li> </ul> <p>This is often labeled a <code>greatest-n-per-group</code> query, and it comes up frequently on Stack Overflow. Here's a solution that I tested for your test data, but you can follow the tag I added to your question for other solutions and discussion.</p> <p><strong>edit:</strong> I missed the requirement for both opening price and closing price. The following is edited.</p> <pre><code>SELECT DATE_FORMAT(C.`DTE`, '%m/%d/%Y') AS trading_day, MIN(C.`PRICE`) AS min_price, MAX(C.`PRICE`) AS max_price, Copen.`PRICE` AS opening_price, Cclose.`PRICE` AS closing_price FROM `CHART_DATA` AS C INNER JOIN `CHART_DATA` AS Cclose ON DAY(C.`DTE`) = DAY(Cclose.`DTE`) LEFT OUTER JOIN `CHART_DATA` AS Cclose_later ON DAY(C.`DTE`) = DAY(Cclose_later.`DTE`) AND Cclose.`DTE` &lt; Cclose_later.`DTE` INNER JOIN `CHART_DATA` AS Copen ON DAY(C.`DTE`) = DAY(Copen.`DTE`) LEFT OUTER JOIN `CHART_DATA` AS Copen_earlier ON DAY(C.`DTE`) = DAY(Copen_earlier.`DTE`) AND Copen.`DTE` &lt; Copen_earlier.`DTE` WHERE Cclose_later.`DTE` IS NULL AND Copen_earlier .`DTE` IS NULL GROUP BY trading_day; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload