Groups | Blog | Home
all groups > sql server mseq > september 2003 >

sql server mseq : Help with SQL query


Calvin Steele
9/15/2003 12:14:15 PM
I am trying to query a table to get records sorted in a certain way. There
are two kinds of records - A and B. I want A's to be sorted on "Start Date"
and B's sorted on "End Date". And B's should follow A's.

So, Lets say the table looks like:

Name StartDate EndDate
----------------------------
A1 9/12 9/21
B1 9/12 9/30
A2 9/05 9/25
B2 9/15 9/25

The query should return:

Name StartDate EndDate
----------------------------
A2 9/05 9/25
A1 9/12 9/21
B2 9/15 9/25
B1 9/12 9/30

Can anyone help me please!
Thanks a lot.

Regards,
Calvin

Vishal Parkar
9/15/2003 3:23:10 PM
Try:

create table #t (name varchar(500), startdate datetime, enddate datetime)

insert into #t
select 'A1', '20030912','20030921' union all select
'B1', '20030912', '20030930' union all select
'A2', '20030905', '20030925' union all select
'B2', '20030915', '20030925'

--Required query

select * from
(select 1 idd,name, startdate, enddate
from #t where name like 'A%'
union all
select 2,name, startdate, enddate
from #t where name like 'B%' ) AA
order by idd,case left(name,1) when 'A' then startdate when 'B' then enddate
end


- Vishal

[quoted text, click to view]

Calvin
9/15/2003 4:43:54 PM
Thanks Vishal, that worked.
I have one other question:

What if I wanted to sort by desc on end date for B?

I tried this but it didnt work:

***
order by
idd,
case left(name,1)
when 'A' then startdate
when 'B' then enddate desc
end

SQL server is not taking this desc after the enddate.

Thanks,
Calvin



[quoted text, click to view]
Vishal Parkar
9/15/2003 5:53:56 PM
select * from
(select 1 idd,name, startdate, enddate
from #t where name like 'A%'
union all
select 2,name, startdate, enddate
from #t where name like 'B%' ) AA
order by idd,case left(name,1) when 'A' then startdate end asc, --check this
clause
case left(name,1) when 'B' then enddate end desc --check this clause


- Vishal


[quoted text, click to view]

AddThis Social Bookmark Button