日期:2014-05-18  浏览次数:20614 次

sqlserver怎么查找最后一次
一个报价表tb1:
字段:
id 自动编号(主键)
wuliaoName 物料名称
gongid 供应商
price 价格
date 日期

id wuliaoName gongid price date
1 W1 G1 500 2012-7-1  
2 W2 G2 200 2012-7-2 ----  
3 W2 G5 300 2012-7-2 ----  
4 W1 G1 399 2012-7-3 ----  
5 W1 G3 100 2012-7-4 ----
7 W3 G4 600 2012-7-4  
8 W3 G4 300 2012-7-5 ----  

现在需要找到不同物料,不同供应商,最后日期价格,然后用全部显示到页面上
比如,表中需要显示后面有红色标记都要显示,现在要确保 1.物料一样,供应商不同要显示, 2.物料 和 供应商 一致的选最后日期。
需要的结果:
id wuliaoName gongid price date
2 W2 G2 200 2012-7-2 ----  
3 W2 G5 300 2012-7-2 ----  
4 W1 G1 399 2012-7-3 ----  
5 W1 G3 100 2012-7-4 ----
8 W3 G4 300 2012-7-5 ----

我自己用
第一步先查找 wuliaoName 和 gongid 一一对应,排除重复的,
第二步然后再根据一一对应的wuliaoName 和 gongid 查找最后日期的id,
第三步然后把这些id保存在字符串中,然后再表中where id in(字符串)。得出结果。
这样是可以实现,但是现在光物料就有1万个,供应商几千个,再第二步的时候就已经卡死了。
有没有办法能实现这个结果呢?

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

--wuliaoName gongid

select *
from tb1 t
where not exists (select 1 from tb1 where wuliaoName = t.wuliaoName and gongid = t.gongid and date > t.date)

------解决方案--------------------
SQL code
select *  from tb1  where exists (select wuliaoName, gongid,max(date) from tb1 group by wuliaoName ,gongid)

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

select id,wuliaoName,gongid,price,date
    from t
    where t.date=(select max(date) from t t1 where t.wuliaoName=t1.wuliaoName
        and t.gongid=t1.gongid)

------解决方案--------------------
SQL code
select
 id,wuliaoName,gongid,price,date
from
 tb1 t
where
 date=(select max(date) from tb where t.wuliaoName=wuliaoName and t.gongid=gongid)

---字段可以加索引

------解决方案--------------------
好吧,脑抽了 上面两个是错误的 这个是最后版 ⊙﹏⊙b汗
SQL code


select t1.wuliaoName,t1.gongid,t1.price,t1.date from tb1 t1,
    (select wuliaoName,gongid,max(date) as date from tb1 group by wuliaoName,gongid) t2 
         where t1.wuliaoName = t2.wuliaoName and t1.gongid = t2.gongid and t1.date = t2.date;

------解决方案--------------------
探讨

引用:
SQL code


--wuliaoName gongid

select *
from tb1 t
where not exists (select 1 from tb1 where wuliaoName = t.wuliaoName and gongid = t.gongid and date > t.date)

您的应该是对的。但是我用我的……