1

I have query that is returning the follwing data:

Number  WeekNumber  Date
1111    23          9/11/12 11:01 AM
1111    23          9/11/12 11:58 AM
2222    24          9/17/12 10:14 AM
2222    24          9/18/12 9:52 AM
2222    24          9/19/12 9:46 AM
2222    24          9/20/12 9:42 AM

However what I want is to get the latest date for each week, the result should be:

Number  WeekNumber  Date
1111    23          9/11/12 11:58 AM
2222    24          9/20/12 9:42 AM

What could I use to obtain this. I have tried to use MAX(DATE) but what I am obtaining is the latest date, not the latest date for each week. I have tried with distinct too but I couldn't make it work with the WHERE clause.

Thank you very much.

4

2 に答える 2

5
SELECT Number, WeekNumber, MAX([Date])
FROM TableName
GROUP BY Number, WeekNumber

You're close with the MAX(Date), however you then need to GROUP BY the other details.

于 2012-09-21T09:18:10.777 に答える
1

との間の明らかな1:1の関係はNumberWeekNumber投稿したデータのアーティファクトであり、実際のデータには実際には当てはまらないとあなたは言います。その場合、単純なGROUPBYは答えを提供しません。

分析関数を使用するRDBMSのフレーバーを使用している場合、これは機能します。

select distinct number
       , weeknumber
       , max(date) over (partition by weeknumber) as weekly_max_date
from yourtable;

分析がない場合は、相関サブクエリを使用する必要があります。

select distinct t.number
       , t.weeknumber
       , q.weekly_max_date
from yourtable t
     join ( select weeknumber, max(date) as weekly_max_date
            from yourtable
            group by weeknumber) q
     on (q.weeknumber = t.weeknumber)
于 2012-09-21T09:20:28.327 に答える