0

I have this table:

| DAY | TRIMESTER |

Day is an integer value, always increasing (it counts the seconds passing from day 0). TRIMESTER contains a String value ('FIRST','SECOND','THIRD',etc). I need to get the list of trimesters in the right order.

SELECT DISTINCT TRIMESTER FROM table

returns:

| TRIMESTER |
|   FIRST   |
|   THIRD   |
|   SECOND  |

I have assessed that this would solve my problem:

SELECT  DISTINCT TRIMESTER, SUM(DAY) FROM table GROUP BY TRIMESTER ORDER BY SUM(DAY)

Is there a nicer solution which would output what I need and that would require less computing done by the database? The database is Oracle 11g and the tables are supposed to become very big.

SAMPLE DATA:

| DAY | TRIMESTER |
|  0  |  FIRST    |
|  10 |  FIRST    |
|  12 |  FIRST    |
|  20 |  FIRST    |
|  30 |  SECOND   |
|  35 |  SECOND   |
|  46 |  THIRD    |

I need to get in order: 'FIRST','SECOND' and 'THIRD'. Anyway I have no control over the keys in the TRIMESTER column. They are strings and might just be any string, I can't order them by name. I only know that they cover a "range" of DAY values. E.g. if I had values of "DAY" between 31 and 34 in the example, they'd all have a "SECOND" value in the trimester column.

4

2 回答 2

1

使用GROUP BY

select TRIMESTER 
from MyTable 
group by trimester 
order by max(DAY)

SQL 小提琴示例 #1

使用RANKPARTITION

SELECT TRIMESTER
FROM (
  SELECT TRIMESTER,
  RANK() OVER (partition by TRIMESTER ORDER BY DAY DESC) DAYRANK
  FROM MyTable)
WHERE DAYRANK = 1;

SQL 小提琴示例 #2

于 2012-08-16T15:28:36.723 回答
0

这应该这样做:

SELECT   TRIMESTER
FROM     MY_TABLE
GROUP BY TRIMESTER
ORDER BY MIN (DAY);
于 2012-08-16T16:04:32.770 回答