0

I want to run a SQL query on the following set of data

date creation_date value ------------------------------------ 2018-01-01 2017-05-05 1 2018-01-02 2017-05-05 0 2018-01-03 2017-05-05 1 2018-01-04 2017-05-05 0 2018-01-05 2017-05-05 1 2018-01-06 2017-05-05 1 2018-01-02 2017-05-11 5 

I want to get the following results

2018-01-01 2017-05-05 1 2018-01-02 2017-05-11 5 2018-01-03 2017-05-05 1 2018-01-04 2017-05-05 0 2018-01-05 2017-05-05 1 2018-01-06 2017-05-05 1 

Basically I want to get all the dates, group it by dates and get the latest creation date and get the value for that creation date.

I tried

select date, max(Creation_date), value from datasource group by date, blocked 

but that doesn't do it.

2
  • 1
    what if there are many rows containing the latest Creation_Date? Commented Nov 15, 2017 at 10:29
  • @Hadi Many rows contaning the latest Creation_Date? Please explain... Commented Nov 15, 2017 at 10:40

2 Answers 2

2

I think you can use query like this:

select * from ( select * , row_number() over (partition by date, blocked order by creation_date desc) seq from datasource) t where t.seq = 1; 

SQL Server Fiddle Demo

Sign up to request clarification or add additional context in comments.

2 Comments

if there are many rows containing the latest Creation_Date, this will choose one row randomly. But according to the OP informations provided, this solves the issue
@Hadi if you want all of them you can use rank() function instead ;).
1

Try to use subquery and join with it

SELECT d.* FROM datasource d JOIN ( SELECT [date],MAX(Creation_date) LastCreationDate FROM datasource GROUP BY [date] ) l ON d.[date]=l.[date] AND d.Creation_date=l.LastCreationDate 

Or the second variant if Creation_date is common for all the [date]

SELECT * FROM datasource WHERE Creation_date=(SELECT MAX(Creation_date) FROM datasource) 

5 Comments

the second query will throw an exception if the are many dates = Max(Creation_Date)
@Hadi - It isn't possible. I use aggregate function MAX without GROUP BY - the subquery returns only one row.
SELECT * FROM datasource WHERE Creation_date = .... if there are Many rows that contains the latest creation date, this will not return one row for each date, which is required by the OP
@mko - What about the first query? I wrote "Or the second variant if Creation_date is common for all the [date]".
@Leran2002 first query is fine

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.