问题
I am having data as below
**Heading Date**
A 2009-02-01
B 2009-02-03
c 2009-02-05
d 2009-02-06
e 2009-02-08
I need rank as below
Heading Date Rank
A 2009-02-01 1
B 2009-02-03 2
c 2009-02-05 1
d 2009-02-06 2
e 2009-02-07 3
As I need rank based on date. If the date is continuous the rank should be 1, 2, 3 etc. If there is any break on dates I need to start over with 1, 2, ...
Can any one help me on this?
回答1:
SELECT heading, thedate
,row_number() OVER (PARTITION BY grp ORDER BY thedate) AS rn
FROM (
SELECT *, thedate - (row_number() OVER (ORDER BY thedate))::int AS grp
FROM demo
) sub;
While you speak of "rank" you seem to want the result of the window function row_number().
- Form groups of consecutive days (same date in
grp
) in subquerysub
. - Number rows with another
row_number()
call, this time partitioned bygrp
.
One subquery is the bare minimum here, since window functions cannot be nested.
SQL Fiddle.
Note that I went with the second version of your contradictory sample data. And the result is as @mu suggested in his comment.
Also assuming that there are no duplicate dates. You'd have to aggregate first in this case.
回答2:
Hi this is not correct answer, I am trying.. It is interesting..:) I am posting what I got so far: sqlfiddle
SELECT
rank() over (order by thedate asc) as rank,
heading, thedate
FROM
demo
Order by
rank asc;
Now I am trying to get the break in dates. I don't know how? But may be these links useful
- SQL — computing end dates from a given start date with arbitrary breaks
- How to rank in postgres query
I will update if I got anything.
Edit:
I got this for mysql, I am posting this because it may helpful. Check Emulate Row_Number() Here
Given a table with two columns i and j, generate a resultset that has a derived sequential row_number column taking the values 1,2,3,... for a defined ordering of j which resets to 1 when the value of i changes
回答3:
Bangalore BLR - Bagmane Tech Park 2013-10-11 Data Centre 0 Bangalore BLR - Bagmane Tech Park 2013-10-11 BMS 0 Bangalore BLR - Bagmane Tech Park 2013-10-12 BMS 0 Bangalore BLR - Bagmane Tech Park 2013-10-15 BMS 3
I am having data lyk this..
If last column is zero the rank should be made based on all columns..If the date is continuous like 2013-10-11 ,2013-10-12 rank should be 1,2...
If there is any break in date 2013-10-11 ,2013-10-12 and 2013-10-15 again the rank should start from 1 for 2013-10-15
来源:https://stackoverflow.com/questions/20063524/rank-based-on-sequence-of-dates