Click here to Skip to main content
15,881,424 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
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 sort and select the data in such a way as to get one value per minv_code. The output should look like:
first row:       873939 'Meter'    '7/24/2015 3:31:22'
second row:      873940 'Tamper'   '7/24/2015 3:31:22'

then the rest of the columns
can somebody help me in this
Posted
Updated 3-Aug-15 9:07am
v2

Since you're using Microsoft SQL Server 2008 R2, another alternative would be to use the ROW_NUMBER function[^]:
SQL
WITH cteSortedValues As
(
  SELECT
    minv_code,
    alert_msg,
    alert_time,
    ROW_NUMBER() OVER (PARTITION BY minv_code ORDER BY alert_time DESC) As RN
  FROM
    @Table
)
SELECT
  minv_code,
  alert_msg,
  alert_time
FROM
  cteSortedValues
WHERE
  RN = 1
;

Demo[^]
 
Share this answer
 
Try:
SQL
SELECT m.* From MyTable m
INNER JOIN
   (SELECT minv_code, MAX([date]) AS [date] FROM myTable GROUP by minv_code) g
   ON m.minv_code = g.minv_code AND m.[date] = g.[date]
   ORDER BY minv_code ASC
 
Share this answer
 
SQL
select minv_code, alert_msg, alert_time
from table1 u1
where alert_time = (select max(alert_time)
                     from table1 u2
                    where u1.minv_code = u2.minv_code)

order by minv_code

DEMO[^]
 
Share this answer
 
SQL
select a.minv_code,a.alert_msg,a.alert_time from(
select minv_code,alert_msg,alert_time,ROW_NUMBER() over(partition by minv_code order by alert_time desc) as rr from TABLE1123)a
where a.rr=1
 
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