Click here to Skip to main content
15,884,472 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: , +
i have table that has rows as below

SQL
DECLARE @Table TABLE
(minv_code INT,
 alert_msg varchar(10),
 alert_time Datetime)

 INSERT INTO @Table VALUES
 (873939, 'Reverse', '7/24/2015 3:31:18'),									
 (873939, 'Tamper',  '7/24/2015 3:30:00'),									
 (873939, 'Meter',   '7/24/2015 3:31:22'), 
 (873940, 'Reverse', '7/24/2015 3:30:00'),
 (873940, 'Tamper',  '7/24/2015 3:31:22') 


i want to select the data priority wise
e.g
first row - 873939, 'Meter', '7/24/2015 3:31:22'
second row - 873939, 'Tamper', '7/24/2015 3:30:00'
third row - 873939, 'Reverse', '7/24/2015 3:31:18'
fourth row -873940, 'Tamper', '7/24/2015 3:31:22'      
fifth row - 873940, 'Reverse', '7/24/2015 3:30:00'
Posted
Updated 1-Aug-15 8:00am
v2
Comments
PIEBALDconsult 1-Aug-15 14:05pm    
Rows in a database have no intrinsic "order"; you need to impose some order on them. In this case, do you want to ORDER BY minv_code and alert_msg?
You will likely need to create a table that defines the "priority" of the alert_msg values.

One way is to add a table which defines the order messages and use that lookup table to sort the data.

Consider the following
SQL
DECLARE @Table TABLE
(minv_code INT,
 alert_msg varchar(10),
 alert_time Datetime)

 INSERT INTO @Table VALUES
 (873939, 'Reverse', '7/24/2015 3:31:18'),
 (873939, 'Tamper',  '7/24/2015 3:30:00'),
 (873939, 'Meter',   '7/24/2015 3:31:22'),
 (873940, 'Reverse', '7/24/2015 3:30:00'),
 (873940, 'Tamper',  '7/24/2015 3:31:22')

 select a.minv_code, a.alert_msg, a.alert_time
 from @Table a,
      (select 1 as ordinal, 'Meter' as alert_msg union all
       select 2 as ordinal, 'Tamper' as alert_msg union all
       select 3 as ordinal, 'Reverse' as alert_msg) b
where a.alert_msg = b.alert_msg
order by a.minv_code, b.ordinal;
 
Share this answer
 
SQL
select * from  Table1 order by minv_code, 
   case when alert_msg ='Meter' then 1
        when  alert_msg ='Tamper' then 2
        when  alert_msg ='Reverse' then 3 end;


DEMO[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900