按SQL Server2008中的最新dateTime值选择一个值

时间:2013-05-21 18:38:08

标签: sql-server datetime

我在SQL Server中有表,如下所示。表名:LANDS

Land_ID   UID             DM_DATE              DEL_REASON
   1       5     2013-05-21 20:31:53.773        Reason1
   1       1     2013-05-21 20:45:21.610        Reason2
   1       1     2013-05-21 20:45:27.613        Reason3

我想获取最新DM_DATE的DEL_REASON(获取上次输入日期的原因值),表示(Reason3)。

我写了这个select语句,但它给了我这个错误"An expression of non-boolean type specified in a context where a condition is expected, near ')'"

select [DEL_REASON] from [LANDS] where [Land_ID]='1' AND [UID] ='1' AND MAX([DM_DATE]) 

有人可以提供帮助。

4 个答案:

答案 0 :(得分:1)

通常我会在另一个查询中获取最大日期并自行加入:

select l.del_reason
from lands l
    join (
        select max(dm_date) maxdm_date, land_id, uid
        from lands
        group by land_id, uid
    ) l2 on l.land_id = l2.land_id 
            and l.uid = l2.uid 
            and l.dm_date = l2.maxdm_date
where l.land_id = 1 and l.uid = 1
编辑 - 正如@AaronBertrand建议的那样,另一种替代方法是使用分析ROW_NUMBER()函数,因为您使用的是SQL Server 2008.这将产生比使用MAX更好的性能,因为逻辑读取更少。检查两个查询的执行计划,您将看到使用分析函数查询成本会低得多,特别是当表格大小增加时。

select del_reason
from (
    select del_reason, land_id, uid, 
        row_number() over (partition by land_id, uid order by dm_date desc) rn
    from lands
) l
where l.land_id = 1 and 
    l.uid = 1 and
    l.rn = 1

或许甚至可能更简单:

select del_reason
from (
    select del_reason, 
        row_number() over (order by dm_date desc) rn
    from lands
    where land_id = 1 and uid = 1
) l
where l.rn = 1

答案 1 :(得分:1)

查询:

<强> SQLFIDDLEExample

select TOP 1 [DEL_REASON] 
from [LANDS] 
where [Land_ID]='1' 
AND [UID] ='1' 
ORDER BY [DM_DATE] DESC 

结果:

| DEL_REASON |
--------------
|    Reason3 |

答案 2 :(得分:0)

我喜欢使用公用表表达式来消除子查询。

with max_date (land_id,uid,max_date)
as
(
    select land_id, uid, max(dm_date)
    from LANDS
    group by land_id,uid
)

select del_reason
from LANDS
inner join max_date
on LANDS.land_id = max_date.land_id
and LANDS.uid = max_date.uid
and LANDS.dm_date = max_date.max_date

答案 3 :(得分:-1)

第一

select [DEL_REASON] from [LANDS] where [Land_ID]='1' AND [UID] ='1' AND MIN([DM_DATE])

第二

  

我编写了这个select语句,但是它给了我这个错误“在预期条件,附近'的上下文中指定的非布尔类型的表达式)'”

回答这是因为您的[UID]数据类型可能已在布尔值中声明 检查数据库,如果[UID]在布尔值中,则将其更改为int

希望这能帮到你