SQL更新最小值所在行的数据

假设以下数据,如何用SQL,按PN分组选出最小值,在Check列设为1,条件为:
1、Price的最小值,如第一行;
2、在Price最小值一样的情况下,选Date最小的行,如第3行。
3、已经有Check=1的数据,则不需再更新。(如下表中PN=001、002)

PN CODE Price Date Check
001 A02 11.1 2013/7/16 1
001 A03 11.3 2013/7/15
002 A03 15.5 2013/7/15 1
002 A04 15.5 2013/7/23
002 A02 15.6 2013/7/15
003 A03 12.1 2013/7/10 找出这个并标记为1
003 A04 12.3 2013/7/11
我是在EXCEL中使用VBA执行,当然用程序来判断也可以,想学学SQL的处理方法。

--楼主这个需求 不是很难 需要指出的是:已经有Check=1的数据,则不需再更新

--没有必要这么判断 把1更新为1 并没什么影响 而且如果要排除的话 语句会更长 影响性能
--处理思想就是 不用判断 满足条件就更新 你只需把tbname 改为你的表名就可以了
--有什么问题可以随时问我 希望采纳
with tmp as(select pn,price,date ,row_number() over (partition by price order by date asc) bz
from (
select pn,price,min(date) date from tbname group by pn,price) a)
update a set a.check=bz
from tbname a join tmp b on a.PN=b.PN and a.price=b.price and a.date=b.date追问

我是在EXCEL的VBA中使用,可否转换成ADO中使用的语句?
另关于不更新的问题是有些数据是以前手工选择的,不能修改以往决定的数据。

追答

不明白你的意思 你更新 肯定是以往的数据啊 为什么又不更新呢
VBA我没用过 在sql中处理后 复制过去不行吗?

温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-07-13
比较繁琐(可能我技术不过硬),建议加上唯一标示列,那样会方便很多,筛选出合适的数据行就可以依据标示更新了,现在这表结构,找出了正确数据,想要更新也很麻烦,SQL Server的语句:
update test set Check=d.Check from test c,(
select a.PN,a.Price,min(a.Date) as Date,1 as Check from test a inner join(
select PN,MIN(Price) as Price from test where PN not in (
select distinct PN from test where Check=1
) group by PN) b on a.PN=b.PN and a.Price=b.Price
group by a.PN,a.Price) d
where c.PN=d.PN and c.Price=d.Price and c.Date=d.Date
不知道你用的是什么数据库,我用SQL Server建测试表的时候,字段是不能用Check的,这段SQL仅供参考,大致思路是先分组找出每组最小价格(剔除Check=1的分组)然后inner join 再连接一下表,筛选出价格最小数据行最小日期,更新时依据这个结果更新符合条件的数据行追问

谢谢你的回答!我是在EXCEL的VBA中使用,转换为以下的程序显示Update错误,能否帮忙看看呢?

用[test$]代替 test ,文字COPY上来超过字数限制,只能上图了。

错误信息

追答

不好意思,没用过,我是在SQL Server 2008里边写的

本回答被提问者采纳
第2个回答  2013-07-13
SQL语句加上条件和排序
select * from 表 where check<>'1' order by pn,date
第3个回答  2013-07-13
update table
set [check] = '1'
where [date] =
(
select min([date])
from table
where [check] is null

)
and [check] is null
;