2013-07-17 31 views
0

我有一個用戶登錄的tblData。在表中它們可以是IN或OUT。 我要的是顯示當前登錄的用戶。在SqlServer中查詢用戶當前登錄

enter image description here

+0

我想你應該只是使保持「IN」標識的另一個表和'Out'Id將記錄保存在tbldataRecords表中。 – Pakk

回答

1
Declare @a table ([Date] date,[Time] Time(7),[Type] varchar(10),ID int, Location int) 

Insert into @a Select '20130101','10:00','IN',280,2 
union Select '20130101','11:00','IN',280,2 
union Select '20130101','12:00','OUT',280,2 
union Select '20130101','12:00','IN',111,2 
union Select '20130101','12:00','OUT',1,2 
union Select '20130101','13:00','IN',1,2 


Select * from @a a2 
JOIN 
(
Select MAX(Cast([Date] as dateTime)+[Time]) DT,ID 
from @a 
Group by ID 
) b 
on b.ID=a2.ID and Cast(a2.[Date] as dateTime)+a2.[Time] = b.DT 
Where a2.Type='IN' 
+0

錯誤:數據類型date和varchar在添加運算符中不兼容。 – Apollo

+0

如果要在Varchar字段中存儲日期和時間值(不應該這樣做),您將必須對它們進行Cast [CAST和CONVERT](http://msdn.microsoft.com/zh-cn/library/aa226054(v = sql.80)的.aspx)。但我建議使用本地數據類型。我自己會將Date和Time一起存儲在一個DateTime flield中。 – bummi

+0

我的日期是類型日期和時間是類型的時間(7) – Apollo

1
SELECT * 
FROM tblData E 
WHERE E.date = convert(date, getdate()) 
and convert(time, E.time) <= convert(time, getdate()) 
and E.type = 'IN' 
not exists(
    select 'x' from tblData U 
    where U.id = E.id 
    and U.type = 'OUT' 
    and E.date = U.date 
    and U.time > E.time 
    and convert(time, U.time) <= convert(time, getdate())) 
+0

我得到這個錯誤:關鍵字'not'附近的語法不正確。 – Apollo

+0

+1之前沒有'AND'缺少。除此之外,這可能會解決您的問題 – phoenixgr

0
SELECT 
ID,MAX(convert(datetime,DATE)+' '+TIME) FROM tblData T1 WHERE [Type] = 'IN' AND convert(datetime,DATE)+' '+TIME> 
    (SELECT max(convert(datetime,DATE)+' '+TIME) FROM tblData T2 WHERE T1.ID=T2.ID AND [TYPE]='OUT') 
GROUP BY 
ID 
UNION 
SELECT 
ID,convert(datetime,DATE)+' '+TIME FROM tblData T1 WHERE [Type] = 'IN' AND NOT EXISTS 
    (SELECT convert(datetime,DATE)+' '+TIME FROM tblData T2 WHERE T1.ID=T2.ID AND [TYPE]='OUT') 
+0

第1行給出了這個錯誤:錯誤:數據類型date和varchar在add操作符中不兼容。 – Apollo

+0

我的日期類型是日期和時間類型是時間(7) – Apollo

+0

請再試一次,我很抱歉無法確認之前的數據類型 – Sonam

0
SELECT 
ID,MAX(QDateTime) FROM tblData T1 WHERE [Type] = 'IN' AND QDateTime> 
    (SELECT max(QDateTime) FROM tblData T2 WHERE T1.ID=T2.ID AND [TYPE]='OUT') 
GROUP BY 
ID 
UNION 
SELECT 
ID, QDateTime FROM tblData T1 WHERE [Type] = 'IN' AND NOT EXISTS 
    (SELECT QDateTime FROM tblData T2 WHERE T1.ID=T2.ID AND [TYPE]='OUT')