开发者

Sql Server query with date filter

开发者 https://www.devze.com 2022-12-20 12:30 出处:网络
I have a table like this; ID int, OrderedDate DateTime I want to select only records of followed month. For example result set:

I have a table like this;

ID int,
OrderedDate DateTime

I want to select only records of followed month.

For example result set:

ID    OrderedDate

110    January
110    February
200    January
200    Feb开发者_运维技巧ruary

How can I write this query?


I think you want list of months that ID has orders in but with the months sorted by the month number instead of the name?

create table test21210
(
    id int,
    OrderedDate datetime
)
go

insert test21210 (id, OrderedDate) values (110, '1/1/2010')
insert test21210 (id, OrderedDate) values (110, '1/5/2010')
insert test21210 (id, OrderedDate) values (110, '1/10/2010')
insert test21210 (id, OrderedDate) values (110, '2/2/2010')
insert test21210 (id, OrderedDate) values (110, '2/4/2010')
insert test21210 (id, OrderedDate) values (110, '2/6/2010')

insert test21210 (id, OrderedDate) values (200, '1/3/2010')
insert test21210 (id, OrderedDate) values (200, '1/5/2010')
insert test21210 (id, OrderedDate) values (200, '1/7/2010')
insert test21210 (id, OrderedDate) values (200, '1/9/2010')
insert test21210 (id, OrderedDate) values (200, '2/3/2010')
insert test21210 (id, OrderedDate) values (200, '2/5/2010')
insert test21210 (id, OrderedDate) values (200, '2/7/2010')
insert test21210 (id, OrderedDate) values (200, '2/9/2010')
go

with idmonth (id, MonthNumber) as
(
    select id, MONTH(ordereddate) as 'MonthNumber'
    from test21210
    group by id, MONTH(ordereddate)
)
select id, DATENAME(MONTH, STR(MonthNumber)+'/1/2000')
from idmonth
order by id, MonthNumber


The question seems a bit unclear. But the example makes it look like you are wanting to sort by ID then by month name. If so, then I think this will do it. I don't have SQL Server to test it, so I'm sure it has syntax or other errors.

SELECT ID, DATENAME(month, OrderedDate) AS OrderedDate from table
       ORDER BY 1, MONTH( OrderedDate )
0

精彩评论

暂无评论...
验证码 换一张
取 消