2012-03-30 44 views
0

我有感嘆,並簽署了價值檢索同桌的最小值和最大值的時間在SQL Server

**id Date  Time Status** 
    01 1/02/12 8:10 Entry 
    01 1/02/12 9:00 Exit 
    01 1/02/12 9:10 entry 
    01 1/02/12 17:00 Exit 
    02 1/02/12 8:10 Entry 
    02 1/02/12 9:00 Exit 
    02 1/02/12 9:10 entry 
    02 1/02/12 17:00 Exit 
    **03 1/02/12 17:00 Exit** 

我必須找出只有每個ID的最小值和最大值時間的表

預期結果

**id Date  Entry  Exit ** 
    01 1/02/12 8:10  17:00 
    02 1/02/12 8:10  17:00 

請幫我

此代碼工作正常,但櫃面一個入口追加上LY出口增加則 我想顯示

id Date  Entry Exit 
---- -------- ----- ----- 
01 01/02/12 08:10 17:00 
02 01/02/12 08:10 17:00 
**03 01/02/12 Null 17:00** 

請幫我 在此先感謝

+0

什麼是你列的數據類型? – 2012-03-30 13:06:53

回答

1

像這樣的東西可能會因使用的數據類型的工作。

declare @T table 
(
    id varchar(2), 
    [Date] datetime, 
    [Time] varchar(5), 
    [Status] varchar(5) 
) 

insert into @T 
select '01', '1/02/12', '8:10', 'Entry' union all 
select '01', '1/02/12', '9:00', 'Exit' union all 
select '01', '1/02/12', '9:10', 'entry' union all 
select '01', '1/02/12', '17:00', 'Exit' union all 
select '02', '1/02/12', '8:10', 'Entry' union all 
select '02', '1/02/12', '9:00', 'Exit' union all 
select '02', '1/02/12', '9:10', 'entry' union all 
select '02', '1/02/12', '17:00', 'Exit' 

select id, 
     convert(varchar(8), [Date], 1) as [Date], 
     convert(varchar(5), min([Time]), 108) as [Entry], 
     convert(varchar(5), max([Time]), 108) as [Exit] 
from 
    (
    select id, 
      [Date], 
      cast([Time] as datetime) as [Time], 
      row_number() over(partition by id order by [Date]+cast([Time] as datetime) asc) as rn1, 
      row_number() over(partition by id order by [Date]+cast([Time] as datetime) desc) as rn2 
    from @T 
) as T 
where T.rn1 = 1 or 
     T.rn2 = 1 
group by id, [Date] 

結果:

id Date  Entry Exit 
---- -------- ----- ----- 
01 01/02/12 08:10 17:00 
02 01/02/12 08:10 17:00 
+0

非常感謝,它的工作正常 – kknaufal 2012-04-02 09:07:46

+0

@kknaufal - 聽起來很好。那麼你應該考慮接受答案作爲使用左邊複選標記的正確答案。這將向社區發出這個問題已得到解答的信號。 – 2012-04-02 09:30:08

0

寫像下面

Select * from MyTable where Time = (Select min(Time) from MyTable) and Status = 'Entry' 

Select * from MyTable where Time = (Select max(Time) from MyTable) and Status = 'Exit' 

編輯查詢:

如果你想有一個單一查詢到這樣的值,你可以得到它,如下所示

SELECT DISTINCT MyTable.ID, MyTable.Date, MyTable.Time AS Entry, MyTable_2.Time AS 
[Exit] FROM MyTable CROSS JOIN MyTable AS MyTable_2 WHERE (MyTable.Time = 
(SELECT MIN(Time) AS Expr1 FROM MyTable AS MyTable_1)) AND (MyTable.Status = 'Entry') 
AND (MyTable_2.Time = (SELECT MAX(Time) AS Expr2 FROM MyTable AS MyTable_3)) AND 
(MyTable_2.Status = 'Exit') 
相關問題