我们有一张表''timekeeper'喜欢
id | entry_date
------------------
1 | 1406864087263
1 | 1406864087268
假设entry_date列表示进出时间。我没有使用两列进出,而是使用了一列。这是错误的设计。我接受了。
但我的要求是我想要选择查询来生成输出,如
id | in_time | out_time
1 | 1406864087263 | 1406864087268
即显示与select stmt中的两列相同的列。
有可能实现吗?
答案 0 :(得分:5)
假设您在退出前总是进入,每个身份证只有一个进入和退出。
SELECT id,
Min(entry_time) [in_time],
Max(entry_time) [out_time]
FROM timekeeper
GROUP BY id
链接到sqlfiddle:http://sqlfiddle.com/#!6/a93f5/2
答案 1 :(得分:1)
您可以为in_rows创建一个rownumber,为out_rows创建2,并自行加入in和out行
with table_with_rows as
(
select *, ROW_NUMBER() OVER ( PARTITION BY id ORDER BY entry_date )
as in_out from timekeeper
)
select in_table.id, in_table.entry_date as in_time, out_table.entry_date
as out_time from
table_with_rows in_table
inner join
table_with_rows out_table
on in_table.in_out = 1 and out_table.in_out = 2 and in_table.id = out_table.id
链接到SqlFiddle
答案 2 :(得分:-1)
;WITH CTE
AS
(
SELECT ROW_NUMBER() OVER (PARTITION BY ID ORDER BY LOGINOUT)RNO,ID,LOGINOUT FROM #TEMP
)
SELECT C1.LOGINOUT AS INTIME,C2.LOGINOUT AS OUTTIME FROM CTE C1
LEFT OUTER JOIN CTE AS C2
ON C1.ID = C2.ID+1