按另一列的值分组

时间:2010-04-29 13:46:04

标签: sql-server-2005

我有桌子文章

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

如何转换:

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

获取IDArticle 例如:

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

预期结果是:

art3
art5

不与以下内容重复: Sql query number of occurance

3 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:0)

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) 

答案 2 :(得分:0)

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
相关问题