Domanda

i have the following table where i have the date( not a primary key) and rating ('A' being the highest grade):

   date       rating
03-10-2010      C
03-09-2010      C
03-08-2010      B
03-07-2010      B
03-06-2010      B
03-05-2010      B
03-04-2010      A

I need to make a query where i compare the rating in order to return the result for each 'date'.

For example. considering the date 03-10-2010, i want to know when the last rating downgrade happened. if the downgrade was 1 day ago return '1' as result, if it was 2 days ago return '2' and if was older than 3 days return 0. And i would do the same query for each date, getting an array with the results.

i'm stuck trying to do this and i have no more ideas how to do it. Anyone can help me please? thanks.

È stato utile?

Soluzione

You want the difference, in days, between the date of each record and the date of the record before the last downgrade.

When you have a specific record, the record before the last downgrade is the record that

  • has a higher rating than this record, and
  • has a lower date than this record, and
  • is the latest record of those.

In SQL, this can be done with a correlated subquery:

SELECT date,
       rating,
       (SELECT date
        FROM MyTable AS downgrade
        WHERE downgrade.date < MyTable.date
          AND downgrade.rating < MyTable.rating
        ORDER BY date DESC
        LIMIT 1) AS downgrade_date
FROM MyTable

date        rating      downgrade_date
----------  ----------  ----------
2010-03-04  A                     
2010-03-05  B           2010-03-04
2010-03-06  B           2010-03-04
2010-03-07  B           2010-03-04
2010-03-08  B           2010-03-04
2010-03-09  C           2010-03-08
2010-03-10  C           2010-03-08

To compute the difference, convert the date into a numeric value. You can then use this value for further computations:

SELECT date,
       rating,
       CASE
       WHEN days <= 3 THEN days
                      ELSE 0
       END AS whatever
FROM (SELECT date,
             rating,
             julianday(date) -
             julianday((SELECT date
                        FROM MyTable AS downgrade
                        WHERE downgrade.date < MyTable.date
                          AND downgrade.rating < MyTable.rating
                        ORDER BY date DESC
                        LIMIT 1)) AS days
      FROM MyTable)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top