Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here's one way (lameness quotient calculation left as an exercise to the reader):</p> <pre><code>CREATE TABLE scores (user_id VARCHAR2(32), test_date DATE, score NUMBER); INSERT INTO scores VALUES('U1',SYSDATE-61, 85); INSERT INTO scores VALUES('U1',SYSDATE-31, 89); INSERT INTO scores VALUES('U1',SYSDATE, 92); INSERT INTO scores VALUES('U2',SYSDATE-61, 65); INSERT INTO scores VALUES('U2',SYSDATE-31, 89); INSERT INTO scores VALUES('U2',SYSDATE, 84); COMMIT; SELECT s1.user_id, s1.test_date, s2.score-s1.score delta FROM scores s1 JOIN (SELECT user_id, trunc(test_date,'MM') test_date, score FROM scores) s2 ON (s1.user_id = s2.user_id AND trunc(add_months(s1.test_date,1),'MM') = s2.test_date); USER_ID TEST_DATE DELTA -------------------------------- --------- ---------- U1 9/15/2009 3 U1 8/16/2009 4 U2 9/18/2009 -5 U2 8/19/2009 24 </code></pre> <p><strong>EDIT</strong>: It's a slow afternoon, so I decided to look into this analytic function stuff that 10g offers (further dragging myself into the current century ;-), and rewrote the above using the LAG function:</p> <pre><code>SELECT user_id, test_date, score , LAG(score, 1, NULL) OVER (PARTITION BY user_id ORDER BY test_date DESC) - score delta , LAG(score, 1, NULL) OVER (PARTITION BY user_id ORDER BY test_date DESC) AS next_score FROM scores ORDER BY 1, 2 DESC; </code></pre> <p>Which produces:</p> <pre><code>USER_ID TEST_DATE SCORE DELTA NEXT_SCORE -------------------------------- ----------- ---------- ---------- ---------- U1 10/19/2009 92 U1 9/18/2009 89 3 92 U1 8/19/2009 85 4 89 U2 10/19/2009 84 U2 9/18/2009 89 -5 84 U2 8/19/2009 65 24 89 </code></pre> <p>Look, Ma! No self-join! Now THAT's slick ;-) (As an aside, the explain plans indicate the self-join is not as efficient).</p> <p>As a springboard, I started with this <a href="http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:16389714357623" rel="nofollow noreferrer">asktom.com question</a>.</p>
    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