日期:2014-05-17  浏览次数:20405 次

怎样和上期的数据对比
如何根据时间选择相应的行?
  ContractTable(合同表)包含下列字段:1、ContractNumber(合同号,主键,Nvarchar);2、City(所在城市,Nvarchar);3、Road(所在路段,Nvarchar);4、Address(门牌号,Nvarchar);5、LeaseDateTo(合同终止时间,Date);6、MonthRent(月租金)。
   
  -其中City、Road、Address这3个值相加后得到完整的某个门面的地址,在这个地址的基础上和租赁户签合同。合同签订有时间的先后,也就是根据LeaseDateTo(合同终止时间)来排列。
  - 我的问题是:同一个门面随着时间的推移会签订越来越多的合同,那么,我该如何设置筛选条件,使得只显示最新的合同呢

  下面是我的代码及错误提示:
SQL code

;with cte as(
select *
from contractTable a join propertyTable b on a.city+a.road+a.address=b.city+b.road+b.address
)
select * from cte a where not exists(select 1 from cte  where city=a.city and road=a.road and address=a.address and leasedateto>a.leasedateto)



错误提示:消息 8156,级别 16,状态 1,第 1 行
多次为 'cte' 指定了列 'City'。



------解决方案--------------------
SQL code

;with cte as(
select *
from contractTable a join propertyTable b on a.city+a.road+a.address=b.city+b.road+b.address
)  --- 在cte里把需要的列名别名出来 再查询 
select * from cte a where not exists(select 1 from cte  where city=a.city and road=a.road and address=a.address and leasedateto>a.leasedateto)