views:

39

answers:

4

Hi,

I've got table Articles

ID identity autoincement, IDArticle: nvarchar(100) ,IDCar nvarchar(100), createddate

How to convert this:

SELECT IDCar , MAX(createddate)
FROM Articles
GROUP BY IDCar 

to get IDArticle eg:

1 art1 BWM 5-21-2010
2 art2 BMW 5-24-2010
3 art3 BMW 5-31-2010
4 art4 Porshe 5-31-2010
5 art5 Porshe 6-1-2010

Expecting result is:

art3
art5

It's not duplicated with: http://stackoverflow.com/questions/2736769/sql-query-number-of-occurance/2736809#2736809

A: 
SELECT outerTable.IDArticle
FROM Articles outerTable
WHERE outerTable.createddate = 
    (SELECT MAX(innerTable.createddate) 
     FROM Articles innerTable
     WHERE outerTable.IDCar = innerTable.IDCar
     GROUP BY innerTable.IDCar) 
froadie
works if you replace the reserved words: `outer` and `inner` with better table alias names. otherwise SQL Server gives you: `Msg 156, Level 15, State 1, Line 1 Incorrect syntax near the keyword 'outer'.`
KM
@KM - whoops thanks! I'll fix that
froadie
+4  A: 
SELECT a.IDArticle
FROM
(
  SELECT IDCar , MAX(createddate) as max_date
  FROM Articles
  GROUP BY IDCar 
) max
INNER JOIN Articles a ON a.IDCar = max.IDCar and a.createddate = max.max_date
IMHO
+1, but `a.createdate = max.max_date` need to be `a.createddate = max.max_date`
KM
+1 from me. ....
Mitch Wheat
A: 
WITH ArticlesMaxDate (IDCar, MaxCreatedDate) AS
(
    SELECT 
        IDCar , MAX(createddate) AS MaxCreatedDate
    FROM 
        Articles 
    GROUP BY 
        IDCar 
)
SELECT 
    a.IDcar
   , a.IDArticle
   , amd.MaxCreatedDate
FROM
   Articles a
   INNER JOIN ArticlesMaxDate amd ON amd.IDCar = a.IDCar
      AND amd.MaxCreatedDate = a.createddate
Mitch Wheat
using the sample data, this returns 5 rows, you need to add `AND amd.MaxCreatedDate=a.createddate` to the `ON` join
KM
@KM: thanks! that was a typo!
Mitch Wheat
A: 

Use this:

select IDArticle 
from articles o
where createdate = 
    (select max(createdate) from articles where IDCar = o.IDCar)
Michael Buen