如何在sql中使用groupby,distinct

时间:2016-11-25 11:49:05

标签: sql asp.net

This is the table data

表名是voyagemaster。如何选择不同的船只和一艘船只有很多航程号,因此我添加了航行 选择voyagenumber为max(voyagedate)。 根据船只选择max(voyagedate)和voyagenumber。 怎么解决..

select distinct(Vessel), VoyageID, VoyageNumber, max(VoyageDate) as vdate, VIA,
       ROTNo, CutOffDate, CutOffTime, ETA, ETD
from VoyageMaster
group by Vessel 

先谢谢

2 个答案:

答案 0 :(得分:0)

试试这个:

SELECT A.Vessel,V1.VoyageID,V1.VoyageNumber,A.VoyageDate 
FROM VoyageMaster V1 
JOIN ( SELECT Vessel,MAX(VoyageDate) VoyageDate  
       FROM VoyageMaster 
       GROUP BY Vessel ) A 
  ON A.Vessel = V1.Vessel 
  AND V1.VoyageDate = A.VoyageDate

答案 1 :(得分:0)

试试这个:

SELECT * from VoyageMaster
where VoyageDate in (select max(VoyageDate)from VoyageMaster group by vessel) 

或仅包含您想要的列:

SELECT Vessel,VoyageID,VoyageNumber,VoyageDate,VIA,ROTNo,CutOffDate,CutOffTime,ETA,ETD
from VoyageMaster
where VoyageDate in (select max(VoyageDate)from VoyageMaster group by vessel)