2017-01-09 88 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