0

我在 SQL Server 中有如下表。表名:土地

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)。

我写了这个选择语句,但它给了我这个错误"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

4 回答 4

1

询问:

SQLFIDDLE示例

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

结果:

| DEL_REASON |
--------------
|    Reason3 |
于 2013-05-21T18:43:36.173 回答
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
于 2013-05-21T18:41:11.603 回答
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
于 2013-05-21T18:52:57.803 回答
-1

第一

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

第二

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

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

希望这对你有帮助

于 2013-05-21T18:40:43.313 回答