首先是我的sql:
SELECT DISTINCT(CarTable.CarPlate), CarTable.CarImage, EventTable.FirstDate
FROM CarTable JOIN EventTable ON CarTable.CarId = EventTable.CarId
ORDER BY 3 DESC
我正在尝试按日期排序,但工作正常,但我希望所有的印版只能写一次。我的意思是我需要看到所有赛车的最后一场比赛,但似乎我使用了明显的错误。这样做的最佳方式是什么?
答案 0 :(得分:3)
使用MAX
和GROUP BY
:
SELECT
c.CarPlate,
c.CarImage,
FirstDate = MAX(e.FirstDate)
FROM CarTable c
INNER JOIN EventTable e
ON c.CarId = e.CarId
GROUP BY c.CarPlate, c.CarImage
ORDER BY MAX(e.FirstDate) DESC
注意:
答案 1 :(得分:1)
请参阅,如果此工作不使用聚合函数。
SELECT c.CarPlate
,c.CarImage
,ev.FirstDate
FROM CarTable C
CROSS APPLY (
SELECT max(FirstDate) FirstDate
FROM EventTable E
WHERE c.CarId = e.CarId
) ev
ORDER BY ev.FirstDate DESC
答案 2 :(得分:0)
或使用窗口DISTINCT
:
SELECT DISTINCT
C.CarId,
C.CarImage,
MAX(E.FirstDate) OVER (PARTITION BY E.CarId) FirstDate
FROM CarTable C
JOIN EventTable E ON C.CarId = E.CarId
ORDER BY FirstDate DESC