1

I need to do something in SQL and I'm currently confused!

So I have something like this:

idEvent   idService   dateCreated
-------   ---------   -----------
1         1           2012-01-01
2         1           2012-02-02
3         2           2012-01-01
4         2           2012-02-02

The idEvent is auto-incrementing.

What I need to get is the biggest row (ordered by dateCreated DESC) for each idService.

So I'd need to get this as a result :

idEvent
-------
2
4

3 Answers 3

7

You can use a common table expression to apply a "row number" to each idService / dateCreated combination. You didn't specify your table name, so you'll have to fix that.

;WITH x AS 
(
  SELECT idEvent, idService, dateCreated, rn = ROW_NUMBER() OVER 
    (PARTITION BY idService ORDER BY dateCreated DESC)
  FROM dbo.table_something_like_this
)
SELECT idEvent, idService, dateCreated
FROM x
WHERE rn = 1;
0
0

very similar to Aaron's really but it's a small variation on the theme. On FIDDLE HERE

create table the_table 
(
  idEvent INT,
  idService INT,
  dateCreated DATETIME
)

insert into the_table
values
 ( 1, 1, '01 JAN 2012'),
 ( 2, 1, '02 FEB 2012'),
 ( 3, 2, '01 JAN 2012'),
 ( 4, 2, '02 FEB 2012')

SELECT *
FROM 
     the_table a
    INNER JOIN 
        (
        SELECT 
          idEvent
          , rk = RANK() OVER (PARTITION BY idService ORDER BY dateCreated DESC) 
        FROM the_table 
        )b
        ON
        a.idEvent = b.idEvent
        AND b.rk= 1
0

Stealing a little of the code from whytheq, I rewrote it to use a group by and a table variable.

   DECLARE @the_table TABLE
        (
         idEvent INT
        ,idService INT
        ,dateCreated DATETIME
        )

INSERT  INTO @the_table
VALUES  (1,1,'01 JAN 2012'),
        (2,1,'02 FEB 2012'),
        (3,2,'01 JAN 2012'),
        (4,2,'02 FEB 2012')


SELECT  MAX(idEvent)
FROM    @the_table
GROUP BY idService

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.