Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server get column not in Group By clause?

How to get the following result from this table?

ID1|ID2| Date  
----------------------
1  | 1 | 01-01-2014  
1  | 2 | 02-01-2014  
2  | 3 | 03-01-2014

I want to get ID1 & ID2 for the maximum date when grouped by ID1

Result:

1,2  
2,3

My code:

SELECT 
    ID1, MAX(DATE) 
FROM 
    Table 
GROUP BY 
    ID1

I need something like

SELECT 
    ID1, ID2, MAX(DATE) 
FROM 
    Table 
GROUP BY 
    ID1

Can someone help me?

like image 305
Jorge Rodrigues Avatar asked Oct 23 '14 19:10

Jorge Rodrigues


3 Answers

There's three ways to do it.

One, a subquery:

SELECT t1.ID1, t1.ID2, t2.MAX_DATE
FROM Table t1
INNER JOIN (
    SELECT ID1, MAX(DATE) AS "MAX_DATE" FROM Table GROUP BY ID1) t2
    ON t1.ID1 = t2.ID2

Or you can use the OVER() clause if you're on SQL Server 2005+, recent versions of Oracle, or PostgreSQL (and most recent things not MySQL or MariaDB):

SELECT ID1,
    ID2,
    MAX(DATE) OVER(PARTITION BY ID1)
FROM Table

Or you can use a correlated subquery:

SELECT t1.ID1, 
    t1.ID2, 
    (SELECT MAX(DATE) FROM Table WHERE ID1 = t1.ID1)
FROM Table t1
like image 103
Bacon Bits Avatar answered Oct 08 '22 10:10

Bacon Bits


You can accomplish this by joining the table to the aggregate, like this:

SELECT t.*
FROM 
    Table t 
     INNER JOIN 
      (
        SELECT 
            ID1, 
            MAX(Date) MaxDate 
        FROM Table 
        GROUP BY ID1
      ) MaxDate ON
        t.ID1 = MaxDate.ID1 AND
        t.Date = MaxDate.MaxDate
like image 24
AHiggins Avatar answered Oct 08 '22 09:10

AHiggins


you can use ROW_NUMBER analytic function

SELECT *
FROM
(SELECT *,
      ROW_NUMBER() over ( partition by ID1 order by [date] desc) as seq
 FROM Table1
) T
WHERE T.seq =1
like image 24
radar Avatar answered Oct 08 '22 11:10

radar