[英]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.