2010-04-29 56 views
0

我有表文章組通過與另一列的值

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

回答

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

+1,但是'a.createdate = max.max_date'需要從我那裏得到'a.createddate = max.max_date' – 2010-04-29 13:54:57

+0

+1。 ... – 2010-04-29 14:25:34

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) 
+1

作品更換保留字:'outer'和'更好的表別名inner'。否則SQL Server會爲您提供:'Msg 156,Level 15,State 1,Line 1關鍵字'outer'附近的語法不正確.' – 2010-04-29 14:02:03

+0

@KM - 哎喲,謝謝!我會修復 – froadie 2010-04-29 14:05:10

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 
+0

使用樣本數據,這將返回5行,您需要將'AND amd.MaxCreatedDate = a.createddate'添加到'ON'加入 – 2010-04-29 13:59:41

+0

@KM:謝謝!那是一個錯字! – 2010-04-29 14:24:41

相關問題