简体   繁体   English

如何在共享另一列相同值的两行之间比较列值?

[英]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. 例如,表中可以同时存在[John Smith,10/17/17,12/17/17]和[John Smith,01/17/18,02/17/18]。 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: 对于上面的示例,select语句应返回以下内容:

[name, date difference in weeks], with the date difference in this case being 02/17/18 - 10/17/17 [名称,以星期为单位的日期差],在这种情况下,日期差为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 不确定使用的是哪种DBMS,但是如果是SQL Server,并且希望在几周内有所不同,则可以编写以下内容

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;

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

相关问题 我怎样才能 select 所有不与另一行 null 共享列值的行? - How can I select all the rows which do not share a column value with another row which is null? 我如何比较两行并将两行的相似性存储在另一列中 - how do i compare two rows and store the similarities of the two rows in another column 如何比较除一列或两列之外具有相同列值的行之间的日期? - How to compare dates between rows with same column values except one or two columns? SQL:如何比较同一列中两行的对应值? - SQL: how to compare corrosponding values two rows from same column? SQLite:如何更新具有与另一列两行之差的值的列? - SQLite: How can I update a column with a value that is the difference between two rows of another column? 如何比较同一列中不同行的值? - How can I compare values in the same column for different rows? 如果检查的第一列中的两行相同,我如何使用另一列? - How do I use another column if two rows in the first column checked are the same? 比较两行中的列,如果另一列的更改值不同,则进行比较 - Compare column from two rows and if different change values of another column 如何比较同一列的两行 - How to compare two rows with same column 从一列中选择共享另一列中的值的值 - Select values from one column which share a value in another column
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM