SQL帮助,不确定使用什么函数

时间:2017-11-12 21:35:05

标签: sql distinct duration

所以这里我有一个SQL查询,我试图找到一个在项目上工作时间最长的工人

SELECT pw.project_id, pw.worker_id, w.worker_name, DATEDIFF(leavedate, joindate) 'Time Worked in Days' 
FROM projectworker pw 
INNER JOIN worker w ON pw.worker_id=w.worker_id

当我运行查询时,我得到了这个:

project_id  worker_id  workername  Time Worked in Days
1                  1        mx      9
1                  1        mx      1087
1                  2        red     740
1                  3        fed     1522
2                  5        meo     1847
2                 12        bull    1462
4                  3        fed     1126
4                  6        mao     4018
4                  7        polly   1858
4                  3        fed     3318
5                  8        max     365
5                  9        drudge  731
5                  10       max     33
5                  12       bull    428
5                  1        mx      793

正如你在项目1中看到的那样,工人1(mx)工作了两次,一次为期9天,持续1087天。我想知道如何设置我的查询,以便他的名字只显示一次,并结合他的工作时间(这样它显示1096)。我尝试使用SELECT DISTINCT,但这给了我一个错误。有什么建议?很抱歉,如果这是一个微不足道的问题,我是SQL的新手!提前谢谢!

2 个答案:

答案 0 :(得分:0)

您需要使用GROUP BY。要分组的字段为projectIdworkerId,然后选择时间总和

SELECT pw.project_id, pw.worker_id, w.worker_name, SUM(DATEDIFF(leavedate, joindate)) 'Time Worked in Days' 
FROM projectworker pw 
INNER JOIN worker w ON pw.worker_id=w.worker_id
GROUP BY pw.project_id, pw.worker_id, w.worker_name

答案 1 :(得分:0)

你必须总结工作时间。结果将首先以最长的工作时间进行排序。

SELECT pw.project_id, pw.worker_id, w.worker_name, 
       SUM(DATEDIFF(leavedate, joindate)) 'Time Worked in Days' 
FROM projectworker pw 
INNER JOIN worker w ON pw.worker_id=w.worker_id
group by pw.project_id, pw.worker_id, w.worker_name
order by SUM(DATEDIFF(leavedate, joindate)) desc