tags:

views:

33

answers:

2

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    February

How can I write this query?

+1  A: 

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 )
Mark Wilkins
+1  A: 

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
DyingCactus