SQL只查找日期早于的记录

时间:2018-02-27 10:37:13

标签: sql sql-server

我有表InventTrans

专栏:

itemid, datephysical, recordid

我只需找到itemid,其日期datephysical早于01-01-2016,并且不存在任何更新。

我正在尝试这种方式 - 但它无法正常工作。

select ITEMID 
from INVENTTRANS itra
where itra.DATEPHYSICAL <= CONVERT(datetime, '2016-01-01') 
and ITEMID not in (
    select itemid 
    from INVENTTRANS 
    where itra.DATEPHYSICAL >= CONVERT(datetime, '2016-01-01')
)
group by ITEMID

3 个答案:

答案 0 :(得分:2)

只需使用HAVING验证最长日期是否在2016-01-01之前。

select ITEMID 
from INVENTTRANS itra
group by ITEMID
HAVING MAX(DATEPHYSICAL) < CONVERT(datetime, '2016-01-01')

答案 1 :(得分:1)

使用where not exists

select distinct ITEM_ID
from INVENTTRANS t1
where DATEPHYSICAL  < cast('2016-01-01' as date)
and not exists 
  (
   select 1 
   from INVENTTRANS x1 
   where x1.DATEPHYSICAL >= cast('2016-01-01' as date)
   and x1.ITEM_ID = t1.ITEM_ID
  )

答案 2 :(得分:-1)

您需要2016-01-01的旧数据

select ITEMID from INVENTTRANS itra where itra.DATEPHYSICAL < 
CONVERT(datetime, '2016-01-01')