根据相同的行值查找值

时间:2016-03-22 18:15:31

标签: sql ms-access

我有一个包含表格(tblPersonnel)的数据库,其中填充了以下数据。

Name_Personnel      VesselName  SailoutDate Time_transfer   Direction
JB                  Flight 2    3/03/2016   10:38:00        UP
MH                  Flight 2    3/03/2016   10:38:00        UP
RS                  Flight 2    3/03/2016   10:38:00        UP
JB                  Flight 2    3/03/2016   11:40:00        DOWN
MH                  Flight 2    3/03/2016   11:40:00        DOWN
RS                  Flight 2    3/03/2016   11:40:00        DOWN

我需要查询" UP"之间所有人员的总时间。和" DOWN"时间。 我希望得到这样的输出。

Name_Personnel      VesselName  SailoutDate Time_transfer_UP Time_transfer_DOWN  Total_time
JB                  Flight 2    3/03/2016   10:38:00         11:40:00            01:02
MH                  Flight 2    3/03/2016   10:14:00         11:49:00            01:35
RS                  Flight 2    3/03/2016   10:36:00         11:53:00            01:17

Name_personnelvesselnamesailoutdate总是有一个" UP"和" Down"值。所以这些可以用来搜索匹配的行。

我该怎么做?

2 个答案:

答案 0 :(得分:0)

您可以使用条件聚合。挑战是总时间。如果你可以忍受总分钟,那么这很容易:

select Name_Personnel, VesselName, SailoutDate,
       max(iif(direction = 'UP', time_transfer, NULL)) as time_transfer_up,
       max(iif(direction = 'DOWN', time_transfer, NULL)) as time_transfer_down,
       datediff("minute",
                 max(iif(direction = 'UP', time_transfer, NULL)) 
                 max(iif(direction = 'DOWN', time_transfer, NULL))
               ) as minutes_diff
from tblPersonnel
group by Name_Personnel, VesselName, SailoutDate;

答案 1 :(得分:0)

谢谢, 两个答案都运行良好,虽然我看到不同的输出,因为并非所有数据都被完全正确填充。

我最后的询问变成了这个。

SELECT DateDiff("n",Max(IIf([direction]='UP',[time_transfer],Null)),Max(IIf([direction]='DOWN',[time_transfer],Null))) AS minutes_diff, tblPersons.Name_Personnel, tblPersons.VesselName, tblPersons.SailoutDate, tblPersons.Type, tblPersons.VesselName, Max(IIf([direction]='up',[time_transfer],Null)) AS Time_transfer_UP, Max(IIf([direction]='Down',[time_transfer],Null)) AS Time_tranfer_DOWN
FROM tblPersons, QRY_Numberofsailingdays
GROUP BY tblPersons.Name_Personnel, tblPersons.SailoutDate, tblPersons.Type, tblPersons.VesselName, tblPersons.VesselName
HAVING (((tblPersons.SailoutDate) Between [Forms]![FRM_Working_Time_Personnel]![TXT_startdate] And [Forms]![FRM_Working_Time_Personnel]![TXT_enddate]));