简体   繁体   中英

How do I compare column values between two rows which share the same value of another column?

I have a table with these columns:

name, start_date, end_date

In the table there are many rows which share the same name. For example, [John Smith, 10/17/17, 12/17/17] and [John Smith, 01/17/18, 02/17/18] can both exist in the table. What I'm trying to do is given a name, find the earliest start date and the latest end date, and get the difference between these two values and display it as a column.

For the example above, the select statement should return this:

[name, date difference in weeks], with the date difference in this case being 02/17/18 - 10/17/17

You need to group your rows by name:

SELECT name, max(end_date) - min(start_date)
FROM table
GROUP BY name

Not sure what DBMS you are using, but if it is SQL Server, and you want to have difference in weeks, then you can write the following

SELECT name
     , [Date difference in weeks] = DATEDIFF(week, min(start_date), max(end_date))
FROM table
GROUP BY name

Try to use below query.

    select name, max(end_date)-min(start_date)
    from table
    group by name;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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