如何输出样本记录,看起来像预期结果?
示例数据库
Table Sample1
Column Status Int
Column dtDateTime dateTime
Column User varchar(50)
记录
User dtDateTime Status
User1 2017-05-19 08:00:00.000 1
User1 2017-05-19 17:05:00.000 2
User1 2017-05-20 09:05:00.000 1
User1 2017-05-21 17:35:00.000 2
记录1作为时间输入,记录2作为列状态的超时
预期结果
User WORK-DATE Time-IN Time-OUT Status
user1 2017-05-19 08:00:00.000 17:05:00.000 COMPLETE
User1 2017-05-20 09:05:00.000 NULL NO OUT
User1 2017-05-21 NULL 17:35:00.000 NO IN
答案 0 :(得分:2)
我的水晶球提出了这个问题:
SELECT User,
CONVERT(DATE, dtDateTime) AS [WORK-DATE],
CASE WHEN MIN(STATUS) <> MAX(STATUS) THEN 'COMPLETE'
WHEN MAX(STATUS) = 1 THEN 'NO OUT'
WHEN MIN(STATUS) = 2 THEN 'NO IN'
END
FROM Sample1
GROUP BY User, CONVERT(DATE, dtDateTime)
编辑:水晶球没有显示早期的TIME栏
SELECT User,
CONVERT(DATE, dtDateTime) AS [WORK-DATE],
MAX(CASE WHEN STATUS = 1 THEN CONVERT(TIME, dtDateTime) END) AS [TIME-IN],
MAX(CASE WHEN STATUS = 2 THEN CONVERT(TIME, dtDateTime) END) AS [TIME-OUT],
CASE WHEN MIN(STATUS) <> MAX(STATUS) THEN 'COMPLETE'
WHEN MAX(STATUS) = 1 THEN 'NO OUT'
WHEN MIN(STATUS) = 2 THEN 'NO IN'
END AS Status
FROM Sample1
GROUP BY User, CONVERT(DATE, dtDateTime)