2015-06-02 38 views
1

配對的狀態行(有人進入,然後退出),我有一個表user_status,在這裏我插排:狀態(進入/退出網站),什麼時候。表看起來是這樣的:如何在mysql中

id user_id status status_date 
94 5  Entered 2015-03-30 10:43:44 
95 5  Exited 2015-03-30 10:47:38 
96 5  Entered 2015-03-30 10:49:12 
97 3  Entered 2015-03-30 10:51:14 
98 3  Exited 2015-03-30 11:04:12 
99 5  Exited 2015-03-30 11:16:50 
100 3  Entered 2015-03-30 11:20:48 
101 5  Entered 2015-03-30 11:21:37 
102 2  Exited 2015-03-30 11:24:47 
103 2  Entered 2015-03-30 11:25:01 

現在我想創建,針對特定用戶對行匹配他/她已退出狀態進入和返回臨時表的過程。結果應該是這樣的:

id user_id status_date_start status_date_end 
1 5   2015-03-30 10:43:44 2015-03-30 10:47:38 
2 5   2015-03-30 10:49:12 2015-03-30 11:16:50 
3 3   2015-03-30 10:51:14 2015-03-30 11:04:12 
... 

我試過雙內部聯接,遊標上user_status但我沒有管理。請幫忙

+0

我做的,就像你現在正在做的一個項目,我將它們存儲爲充分和原材料表。對於原始表,我存儲A_I,user_id,status_date。我的網站代碼將確定它正在進入或退出。如果它正在進入,我將把'INSERT INTO完整的VALUES('',user_id,last_id,'')'last_id是A_I從原始表中返回。如果它正在退出,我將'更新完整的SET status_date_end = last_id WHERE id = this_id'。 – AkiEru

回答

0

剛剛玩了一下這一點,並得到它在查詢中額外的選擇。

-- set up some test data 
GO 
DECLARE @moves TABLE 
    (
     id INT, 
     user_id INT, 
     status NVARCHAR(MAX), 
     status_date DATETIME 
    ) 

INSERT INTO @moves VALUES (94, 5 , 'Entered', '2015-03-30 10:43:44') 
INSERT INTO @moves VALUES (95, 5 , 'Exited', ' 2015-03-30 10:47:38') 
INSERT INTO @moves VALUES (96, 5 , 'Entered', '2015-03-30 10:49:12') 
INSERT INTO @moves VALUES (97, 3 , 'Entered', '2015-03-30 10:51:14') 
INSERT INTO @moves VALUES (98, 3 , 'Exited', '2015-03-30 11:04:12') 
INSERT INTO @moves VALUES (99, 5 , 'Exited', '2015-03-30 11:16:50') 

-- original data -- 
SELECT * FROM @moves 


-- selecting the exit date into the original data -- 
SELECT 
    m.id 
    ,m.user_id 
    ,m.status_date 
    ,(
     SELECT TOP 1 status_date 
     FROM @moves x 
     WHERE x.user_id = m.user_id 
     AND x.status = 'Exited' 
     AND x.id > m.id 
    ) as 'exit' 
FROM @moves m 
WHERE m.status ='Entered' 

結果:

enter image description here

+0

我使用mysql,所以唯一的改變是將TOP 1更改爲LIMIT 1並且它可以正常工作!謝謝@JensB,你太棒了 – zofia