简体   繁体   English

如何在MSSQL中获得最早的一列并获得最新的另一列

[英]How to get earliest of one column and get latest of another column in MSSQL

When I run this query : 当我运行此查询时:

select * from customertravel where PersonID in (1,2,7)

I get this : 我得到这个:

在此处输入图片说明

But I want to filter results to be like this : 但是我想过滤结果是这样的:

在此处输入图片说明

How should I modify that query to get first arrive date and last leave date? 我应该如何修改该查询以获取第一个到达日期和最后一个离开日期? I know I need to do some group by but I couldn't figure how to use it.. Thnkas in advance.. 我知道我需要做一些分组,但是我不知道如何使用它。

Supposing your ArriveDate and LeaveDate are dates and not strings or so, you could try the following: 假设ArriveDateLeaveDate是日期而不是字符串,则可以尝试以下操作:

SELECT   PersonID,
         Name,
         City,
         MIN(ArriveDate),
         MAX(LeaveDate)
FROM     customertravel
WHERE    PersonID IN (1, 2, 7)
GROUP BY PersonID,
         Name,
         City;

You need to group by all columns except the dates, and find MIN and MAX . 您需要按日期以外的所有列进行分组,并找到MINMAX Just in case your dates are in German format you need to convert them before calculating aggregate: 万一您的日期为德语格式,则需要在计算总计之前进行转换:

SELECT
    PersonID,
    Name,
    City,
    MIN(CONVERT(DATE, ArriveDate, 104)) AS FirstArriveDate,
    MAX(CONVERT(DATE, LeaveDate, 104)) AS LastLeaveDate
FROM customertravel
WHERE PersonID IN (1, 2, 7)
GROUP BY PersonID, Name, City

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM