SQL How to do the ROW ORDER

Hi expert,

I want the table showing the row order by . But the query I use below did not bring the same order. Can you help me on it ? Thanks .

'Customer Sold'
'Lost- Sale'
'Lost-Appointment'
.......


select Reason,  MTD,"Prior Month"  from #temps
 order by case
 when reason='Lost-No Response' then 7
  when reason='Lost- Sale' then 2
   when reason='Lost-Appointment' then 3
    when reason='Lost- Sale' then 4
       when reason='Lost-Car Sold' then 5
              when reason='Customer Sold' then 1
              when reason='Lost-Cold Deal' then 6
              when reason='Lost-Trade Equity' then 8
              when reason='Lost-Working New Deal' then 9
              when reason='Duplicate Deal' then 10
              when reason='Test Deal' then 11
              when reason='Sold- Switched Vehicle' then 12
              when reason='Not Archived Yet' then 13
              end
tanj1035Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Jim HornMicrosoft SQL Server Developer, Architect, and AuthorCommented:
Try this..
ORDER  BY 
   CASE
      WHEN 'Customer Sold' THEN 1
      WHEN 'Lost- Sale' THEN 2
      WHEN 'Lost-Appointment' THEN 3 END

Open in new window

Check out my article on SQL Server CASE Solutions for more examples.
0
tanj1035Author Commented:
Thanks, Jim. I tried yours, but the table still return the different row order.

My query:
IF OBJECT_ID('tempdb..#tempS') IS NOT NULL DROP TABLE #tempS

create table #temps (Reason nvarchar(50),MTD int, "Prior Month" int)
insert into #temps (reason)
(select distinct [ArchiveDealStatus] from mmd_feed..dealviewbyJoy)
update #temps set MTD=0,"Prior Month"=0

merge into #temps MM
 using ( select [ArchiveDealStatus],count(*) as count
  from   [MMD_Feed].[dbo].[DealViewbyjoy] where cast(submittedtimestamp as date)>=DATEADD(MONTH, DATEDIFF(MONTH, 0, Convert(date, getdate())), 0)
  and cast(SubmittedTimeStamp as date)<=Convert(date, getdate()) and dealstatus='sent'   group by archivedealstatus) S on mm.reason=s.archivedealstatus
when matched then
update
set mm.MTD=s.count;


merge into #temps MM
 using ( select [ArchiveDealStatus],count(*) as count
  from   [MMD_Feed].[dbo].[DealViewbyjoy] where cast(submittedtimestamp as date)>=DATEADD(month, DATEDIFF(month, -1, getdate()) - 2, 0)
  and dealstatus='sent'   group by [ArchiveDealStatus]) S on mm.reason=s.[ArchiveDealStatus]
when matched then
update
set mm."Prior Month"=s.count;

select * from #temps
 order by case
 when reason='Customer Sold' then 1
  when reason='Lost- Sale' then 2
   when reason='Lost-Appointment' then 3
    when reason='Lost- Sale' then 4
       when reason='Lost-Car Sold' then 5
              when reason='Lost-Cold Deal' then 6
              when reason='Lost-No Response' then 7
              when reason='Lost-Trade Equity' then 8
              when reason='Lost-Working New Deal' then 9
              when reason='Duplicate Deal' then 10
              when reason='Test Deal' then 11
              when reason='Sold- Switched Vehicle' then 12
              when reason='Not Archived Yet' then 13
              end

The result:
Reason                       MTD          Prior Month
Lost-Credit                10                         62
Customer Sold        28                         216
Lost- Sale                  5                     118
Lost-Appointment      5                40
Lost-Car Sold                   17               159
Lost-Cold Deal        15                        324
Lost-No Response      12               242
Lost-Trade Equity               6                 26
Lost-Working New Deal      7           9
Duplicate Deal                  24      34
Test Deal                          11      17
Sold- Switched Vehicle              8      10
Not Archived Yet                 940      2893
0
Steve WalesSenior Database AdministratorCommented:
Lost-Credit (your first row returned) isn't in the list of your CASE statement.

It will evaluate to NULL I assume and appears first.  The rest appear in order.

Your number 2 & 4, Lost-Sale, appears twice.

Should one of 2 & 4 be Lost-Credit instead of Lost-Sale ?
0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

tanj1035Author Commented:
hi Steve,

You got good eyes. Thanks, I have revised the query, and the "lost-credit still goes to the 1st place. "Lost-credit'  is the value from "ArchiveDealStatus" from mmd_feed..dealviewbyJoy. So, it does not have any null value.


The revised query:

select * from #temps
 order by case
 when reason='Customer Sold' then 1
   when reason='Lost-Appointment' then 2
   when reason='Lost- Credit' then 3
   when reason='Lost-Car Sold' then 4
    when reason='Lost- Sale' then 5      
              when reason='Lost-Cold Deal' then 6
              when reason='Lost-No Response' then 7
              when reason='Lost-Trade Equity' then 8
              when reason='Lost-Working New Deal' then 9
              when reason='Duplicate Deal' then 10
              when reason='Test Deal' then 11
              when reason='Sold- Switched Vehicle' then 12
              when reason='Not Archived Yet' then 13
              end

The result order:

Reason
Lost-Credit
Customer Sold
Lost-Appointment
Lost-Car Sold
Lost- Sale
Lost-Cold Deal
Lost-No Response
Lost-Trade Equity
Lost-Working New Deal
Duplicate Deal
Test Deal
Sold- Switched Vehicle
Not Archived Yet
0
Steve WalesSenior Database AdministratorCommented:
Your strings don't match up.

Your output says "Lost-Credit",  your case says "Lost- Credit" - there's an embedded space in there.

Also, it's not a matter of what the table contains for the null.  You are overriding the value in the column with the case statement and assigning a numeric value.  Since there's not a value assigned by the case and you don't have an ELSE on your case, I'm pretty sure you're going to end up with a NULL there.

If you're doing cases on strings, make sure they match EXACTLY.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
tanj1035Author Commented:
You are right. Thanks, Jim and Steve.
0
Jim HornMicrosoft SQL Server Developer, Architect, and AuthorCommented:
Thanks for the split.  Good luck with your project.  -Jim

Side note:  Is there an ID value you can ORDER BY on, instead of this text value?  Grouping/Ordering on character values with random spaces and dashes in them means YOU ARE PLAYING WITH FIRE, and susceptible to all kinds of duplicate rows/ sorting issues.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server

From novice to tech pro — start learning today.