Share via

SQL Server conditional order by issue

T.Zacks 3,996 Reputation points
2022-01-30T18:27:51.607+00:00

1st set of code


drop table if exists #tmp1
CREATE table #tmp1
(
Ticker VARCHAR(10),
BrokerName VARCHAR(100)
)

insert into #tmp1(Ticker,BrokerName)
VALUES('MTH','JP Morgan'),
('MTH','Morgan Stanley'),
('MTH','Singular Research'),
('MTH','Cowen & Company')

select * from #tmp1
ORDER BY CASE WHEN (Ticker='MTH' AND BrokerName = 'Cowen & Company') THEN 1
ELSE 0 END ASC

drop table if exists #tmp1

this above code is working fine. when Ticker is MTH and broker name is Cowen & Company then broker name is coming at bottom which is perfect as per requirement but when ticker name is other than MTH then all broker name should be sorted ascending order

see second set of code where i try to do it but not working

drop table if exists #tmp1
CREATE table #tmp1
(
Ticker VARCHAR(10),
BrokerName VARCHAR(100)
)

insert into #tmp1(Ticker,BrokerName)
VALUES('GOGO','JP Morgan'),
('GOGO','Morgan Stanley'),
('GOGO','Singular Research'),
('GOGO','Cowen & Company')

select * from #tmp1
ORDER BY CASE WHEN (Ticker='MTH' AND BrokerName = 'Cowen & Company') THEN 1 END,
 CASE WHEN Ticker<>'MTH' THEN 0 END ASC

drop table if exists #tmp1

so please guide how could i write a generic sql where specific broker name should appear at bottom when ticker is MTH but if ticker name is not MTH then broker name should be sorted as ascending order.

thanks

Developer technologies | Transact-SQL
Developer technologies | Transact-SQL

A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.


Answer accepted by question author

Viorel 127K Reputation points
2022-01-30T19:06:57.57+00:00

Try writing this query:

select * from #tmp1
ORDER BY CASE WHEN Ticker='MTH' AND BrokerName = 'Cowen & Company' THEN 1 END, BrokerName

Was this answer helpful?

1 person found this answer helpful.
0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.