我有一张包含以下细节的表格
ID statusID logTime
100238 1 2011-07-07 03:48:43.000
100238 2 2011-07-07 03:48:46.000
100238 1 2011-07-07 09:07:57.000
100238 2 2011-07-07 16:12:28.000
100238 1 2011-07-08 02:59:57.000
100238 2 2011-07-08 03:00:00.000
100238 1 2011-07-08 09:26:37.000
100238 2 2011-07-08 14:03:05.000
并且所需的输出应该像
repID ClockIn ClockOut
100238 2011-07-07 03:48:43.000 2011-07-07 03:48:46.000
100238 2011-07-07 09:07:57.000 2011-07-07 16:12:28.000
100238 2011-07-08 02:59:57.000 2011-07-08 03:00:00.000
100238 2011-07-08 09:26:37.000 2011-07-08 14:03:05.000
ie ..如果statusID为1,则logtime必须在ClockIn列中,如果statusID为2,则logtime必须在ClockOut列中
我使用了像
这样的查询SELECT repID,
ClockIn,
ClockOut from
(SELECT a.eventID,
a.repID,
a.logTime,
CASE WHEN a.statusID = 1 THEN a.logTime ELSE NULL END AS ClockIn,
CASE WHEN b.statusID = 2 THEN b.logTime ELSE NULL END AS ClockOut
FROM tbl_ets_reptimelog a
LEFT JOIN tbl_ets_reptimelog b ON a.repID = b.repID)c
,结果如
repID ClockIn ClockOut
100238 2011-07-07 03:48:43.000 NULL
100238 2011-07-07 03:48:43.000 2011-07-07 03:48:46.000
100238 2011-07-07 09:07:57.000 NULL
100238 2011-07-07 09:07:57.000 2011-07-07 16:12:28.000
100238 2011-07-08 02:59:57.000 NULL
100238 2011-07-08 02:59:57.000 2011-07-08 03:00:00.000
100238 2011-07-08 09:26:37.000 NULL
100238 2011-07-08 09:26:37.000 2011-07-08 14:03:05.000
如何删除在ClockOut Column
中使用NULL值显示的额外行请帮助摆脱这个问题......
答案 0 :(得分:0)
只需在外部查询
中添加WHERE子句即可select repID,ClockIn,ClockOut from(select a.eventID, a.repID, a.logTime,
case when a.statusID = 1 then a.logTime else null end as ClockIn,
case when b.statusID = 2 then b.logTime else null end as ClockOut from tbl_ets_reptimelog a
left join tbl_ets_reptimelog b on a.repID = b.repID)c
WHERE ClockOut IS NOT NULL
答案 1 :(得分:0)
此查询应返回您需要的结果:
SELECT
t1.ID,
t1.logTime check_in,
CASE WHEN MIN(t2.logTime) < MIN(t3.logTime) OR MIN(t3.logTime) IS NULL
THEN MIN(t2.logTime) END check_out
FROM
Logs t1 LEFT JOIN Logs t2
ON t1.ID = t2.ID
AND t2.statusID=2
AND t1.logTime<t2.logTime
LEFT JOIN Logs t3
ON t2.ID = t3.ID
AND t3.statusID=1
AND t1.logTime<t3.logTime
WHERE
t1.statusID=1
GROUP BY
t1.ID, t1.logTime
请参阅小提琴here。