0

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
  • I'm afraid your question is a bit unclear - can you elaborate, please. Commented Feb 12, 2010 at 14:10

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

1

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 )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.