Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <pre><code>SELECT MAX(Date) AS Date , ( SELECT tt.Dept FROM tableX tt WHERE tt.Date = MAX(t.Date) ) AS Dept , SUM(Commission) AS Commission FROM tableX t WHERE Date BETWEEN StartDate AND EndDate </code></pre> <p>The above works in SQL-Server, MySQL, Postgres as the <a href="http://sqlfiddle.com/#!4/7c2e5/16" rel="nofollow">sql-fiddle, test-1</a> shows, however it does NOT work in Oracle 11g R2 !</p> <hr> <p>This works though (<a href="http://sqlfiddle.com/#!4/7c2e5/19" rel="nofollow">sql-fiddle, test-2</a>):</p> <pre><code>SELECT MAX(t.Date) AS Date , MIN(tt.Dept) AS Dept --- MIN, MAX irrelevant , SUM(t.Commission) AS Commission FROM ( SELECT MAX(Date) AS Date , SUM(Commission) AS Commission FROM tableX WHERE Date BETWEEN StartDate AND EndDate ) t JOIN tableX tt ON tt.Date = t.Date </code></pre> <p>The <code>MIN(tt.Dept)</code> is used to take care of the case you have more than row with the maximum date, say one row with <code>Sales</code> and one with <code>Marketing</code>, both in <code>Apr-5</code> </p> <p>This works, too, using the <code>LAST_VALUE</code> analytic function (<a href="http://sqlfiddle.com/?_escaped_fragment_=4/7c2e5/19#!4/7c2e5/33" rel="nofollow">sql-fiddle, test-3</a>):</p> <pre><code>SELECT MAX(Date) AS Date , MIN(Dept) AS Dept , SUM(Commission) AS Commission FROM ( SELECT Date AS Date , LAST_VALUE(Dept) OVER( ORDER BY Date ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING ) AS Dept , Commission AS Commission FROM tableX WHERE Date BETWEEN StartDate AND EndDate ) t </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. 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.
    3. 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