Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
SQL
I've a table with data. The rows are repeated but the change is in only one column(status). Let the status column data be (A, B, C).
Sometimes data will be available with status A, B and C . Then 3 rows will be created for one record(ID=2001). What I need is, If A,B,C are available, the query should return only the row where Status=' A'. Sometimes for another record (ID=2005) B &C will be status. Then I should get row Where Status='B'

How can i tackle this situation with SQLQuery? I'm using SQLServer2008. Any responses will be appreciated.
Posted

If it's always the earliest (alphabetically) record that you want, you could do it like this:

SQL
select ID, min(Status) as Status 
from TABLENAME
group by ID
order by ID
 
Share this answer
 
Comments
Ruggers 28-Jan-14 1:27am    
Thank you for your response. Not like that. Its not alphabetical. The status which I mentioned is an example. Its words actually. So can we provide any priority for the words?
_Damian S_ 28-Jan-14 1:59am    
Words can be alphabeticised... if it needs to be in a particular order, you could somehow work out that order and then do a min from that calculated field... eg:

select ID, min(case Status when 'A' then 1 else 2 end)...
SQL
SELECT * 
FROM (
       SELECT ROW_NUMBER() OVER(PARTITION BY ID ORDER BY [STATUS]) AS RNO, * 
       FROM  <yourtable> /*where ID =2001 AND[STATUS] IN ('A','B','C')*/
     ) X
WHERE RNO =1
</yourtable>

Hope this will also produce what you wnat
 
Share this answer
 
Hi Thava
This is just a suggestion.
If you want priorities for the Status, you'll need an auxiliary table where you can set those priorities as a numeric type.
Then you can join this table with your main table adding a priority column to the result set.
Then you can group select again selecting the MAX(priority) (or MIN depending on how you set the priority order).
All this is done with a query and subqueries.
 
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