[英]Setting two column values from Single Column using sql query
我有一張桌子,上面有以下細節
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
即..如果statusID為1,則日志時間必須在ClockIn列中;如果statusID為2,則日志時間必須在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列中出現NULL值的多余行
請幫助擺脫這個問題......
只需在外部查詢中添加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
此查詢應返回所需的結果:
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
請看這里的小提琴。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.