2017-01-09 92 views
-3

enter image description here選擇SQL表格數據

我有一張如圖所示的表格。這裏用戶'A'沒有外出時間,Id = 2。如果我從MyTable中選擇UserId,Name,MIN(inTime)和MAX(outtime),那麼我將得到First InTime和Last OutTime。而不是像那樣選擇,我想將用戶'A'的最後一次外出時間設置爲空。這怎麼可能?。

由於提前

+0

http://meta.stackoverflow.com/questions/285551/why-may-i-not-upload-images-當問一個問題/ 285557#285557 –

回答

0

我假設你正在使用SQL Server

select * 
from(select name, userid, dateatt 
    from table 
    group by name, userid, dateatt)t 
cross apply(select top 1 intime from table 
      where userid=t.userid and dateatt=t.dateatt order by id)i 
cross apply(select top 1 outtime from table 
      where userid=t.userid and dateatt=t.dateatt order by id desc)o 
+0

謝謝Giorgi Nakeuri,它工作。 – DevinBegin

0

默認情況下,MAX和MIN評估數據時,不包括NULL。

請參閱下面的查詢我爲您修改了文章here

我們將使用COALESCE與是不會被我們的數據的任何地方來了一個未來的日期更換任何NULL結束日期,2099年12月31日似乎是這樣一個合理的日期。接下來我們取MAX的日期,如果NULL將評估爲2015年12月31日並且大於我們表中的任何其他日期。把它放在CASE語句中,將日期12/31/2099替換回NULL,並通過StoreID對我們的數據進行分組。

SELECT Name, CASE WHEN MAX(COALESCE(outtime, ’12/31/2099′)) = ’12/31/2099′ THEN NULL ELSE MAX(outtime) END AS outtime FROM WorkSchedule GROUP BY Name