declare @tb1 table (item varchar(10),[date] char(8),[money] decimal)
insert into @tb1
select 001, 20050617, 10 union all
select 002, 20050617, 20 union all
select 003, 20050617, 33 union all
select 001, 20050618, 11 union all
select 002, 20050618, 21 union all
select 001, 20050619, 12 union all
select 003, 20050619, 32 union all
select 001, 20050620, 13 union all
select 002, 20050620, 22 union all
select 003, 20050620, 31
select
a.*
from
@tb1 a
where
a.[date] = (select max([date]) from @tb1 where item=a.item)
item date money
---------- -------- --------------------
003 20050620 31
002 20050620 22
001 20050620 13
假设你是SQL SERVER,你是怎么个顺序来执行这个查询?先...再...然后...?
Ctrl+L参看执行计划
先是子查询 select max([date]) from @tb1 where item=a.item得到 max值
然后select a.* from @tb1 a where
这个item=a.item是什么意思?
item表示@tb1里面的字段,a.item表示@tb1 a里面的字段。这实际上就是一个自联接,你可以吧它理解为两个不同的表。
上面的语句可以差分为:
select 变量=max([date]) from @tb1,@tb1 a where item=a.item
select * from @tb1 where [date] =变量
在
select
a.*
from
@tb1 a
时查出 a.item
同时 a.item作为子查询where的条件 在子查询里优先级最高
作为 select max([date]) from @tb1的条件
最后查询结果和外面的a.[date]字段做匹配
先 select max([date]) from @tb1 where item=a.item
再 select a.* from @tb1 a where
先取A
然后选择最大
再select a.*
上面写的很明白了 不要以c++的思维去考虑sql sql是结构查询
select max([date]) from @tb1 where item=a.item查出来的东西当然是一条
但item一共有三个 分三次每次一条 最后外面总的记录也是三条