开发者

Query for getting the data

I am a newbee to SQL and need to write a query which seems to be complex. I need to write a 开发者_JAVA百科query for getting the returns from a table which looks like:

 id    Price_date    price   
 1     1-1-2010     20    
 1     2-2-2010     21    
 1     7-2-2010     22    
 1     27-2-2010    23    
 1     3-3-2010     23   

Here is what I need to select from the above table:-

  • id,
  • price_date(date of last price of month),
  • return((last_price_of_month/last_price_of_previous_month) -1),
  • last_date_for_return_calculation(first day of next month)

And the sample data would be like:-

    id      price_date   return        last_date_for_return_calculation    
    1       27-2-2010    (23/20 -1)    1-3-2011     

Could somebody help me in solving this problem?


based on your requirement, it seems your date are in 2011, not 2010. Also I added a row in january to be sure to get the last row of the previous month of the sample data.

SQL> WITH DATA AS (
  2  SELECT 1 id, to_date('1-1-2011', 'dd-mm-yyyy') Price_date, 19.5 price
  3    FROM DUAL
  4  UNION ALL SELECT 1, to_date('31-1-2011', 'dd-mm-yyyy'), 20 FROM DUAL
  5  UNION ALL SELECT 1, to_date('2-2-2011', 'dd-mm-yyyy'), 21 FROM DUAL
  6  UNION ALL SELECT 1, to_date('7-2-2011', 'dd-mm-yyyy'), 22 FROM DUAL
  7  UNION ALL SELECT 1, to_date('27-2-2011', 'dd-mm-yyyy'), 23 FROM DUAL
  8  UNION ALL SELECT 1, to_date('3-3-2011', 'dd-mm-yyyy'), 23 FROM DUAL
  9  )
 10  SELECT ID,
 11         MAX(price_date) price_date,
 12         MAX(price) KEEP (DENSE_RANK FIRST ORDER BY price_date DESC)
 13         / MAX(price)
 14           KEEP (DENSE_RANK FIRST
 15                 ORDER BY CASE WHEN price_date < trunc(SYSDATE, 'month')
 16                               THEN price_date END
 17                 DESC NULLS LAST) - 1 RETURN,
 18         add_months(trunc(SYSDATE, 'month'), 1) last_date_for_return_calc
 19    FROM DATA
 20   WHERE price_date >= add_months(trunc(SYSDATE, 'month'), -1)
 21     AND price_date < add_months(trunc(SYSDATE, 'month'), 1)
 22   GROUP BY ID;

        ID PRICE_DATE      RETURN LAST_DATE_FOR_RETURN_CALC
---------- ----------- ---------- -------------------------
         1 27/02/2011        0,15 01/03/2011


It's possible with a query.

But you're probably better of if you just query the table like that and filter it on your program side.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜