ragehulk ragehulk - 1 year ago 67
SQL Question

How to obtain the "largest day" in a week?

How to get a data when the "largest day" of the week does not exist?

For example, if Friday does not exist in my database for a particular week (assuming that Saturday and Sundays are not in my database), I would still like to be able to get the data from Thursday. If Both Friday and Thursday do not exist, I would like to get the data from Wednesday etc.

This is what I currently have (this code allows me to obtain the last day of the month from my database):

/**Select Last Day Of Month**/
SELECT * FROM [mytable]
WHERE [date] IN (SELECT MAX([date])
FROM [mytable]
GROUP BY MONTH([Date]), YEAR([Date]))

I also understand that you can use the DATEPART function to get all datas from a particular day (i.e. Friday), the thing I'm not sure about is how to get a thursday if Friday doesn't exist. I'm looking to grab all the data that has the corresponding features, not one particular week. Thanks!

As a clearer example:
Say I have four input data in my database->

1. 2016/8/19(Fri), red

2. 2016/8/18(Thu), blue

3. 2016/8/11(Thu), red

4. 2016/8/10(Wed), red

after the query is executed, I would like to have:

1. 2016/8/19(Fri), red

3. 2016/8/11(Thu), red

They are selected because the two data are the corresponding "largest" data in that week.

Answer Source

See if the following query helps. It displays the last day of every week in the given input data.

declare @table table(
date datetime

insert into @table

;with cte as
select date, row_number() over(partition by datepart(year,date),datepart(week,date) order by date desc) as rn from @table

select date,datename(weekday,date) from cte
where rn = 1
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download