日期:2014-05-17 浏览次数:20539 次
---------------------------------
-- Author: HEROWANG(让你望见影子的墙)
-- Date : 2012-10-21 17:58:16
-- blog : blog.csdn.net/herowang
---------------------------------
IF OBJECT_ID('[tb]') IS NOT NULL
DROP TABLE [tb]
go
CREATE TABLE [tb] (billid INT,itemno INT,billcode VARCHAR(5),billdate DATETIME,materialid INT,price NUMERIC(2,1))
INSERT INTO [tb]
SELECT 1,1,'pc001','2012-10-10',10001,2.5 UNION ALL
SELECT 1,2,'pc001','2012-10-10',10003,3.0 UNION ALL
SELECT 3,1,'pc002','2012-10-10',10001,2.6 UNION ALL
SELECT 4,1,'pc000','2012-10-19',10001,2.3
select * from [tb] t
where not exists(select 1 from tb where materialid=t.materialid and price>t.price )
and billdate<='2012-10-19'
CREATE TABLE purchasedetail (billid INT,itemno INT,billcode VARCHAR(5),billdate DATETIME,materialid INT,price NUMERIC(2,1))
INSERT INTO purchasedetail
SELECT 1,1,'pc001','2012-10-10',10001,2.5 UNION ALL
SELECT 1,2,'pc001','2012-10-10',10003,3.0 UNION ALL
SELECT 3,1,'pc002','2012-10-10',10001,2.6 UNION ALL
SELECT 4,1,'pc000','2012-10-19',10001,2.3
SELECT *
FROM purchasedetail a
WHERE EXISTS ( SELECT 1
FROM ( SELECT MAX(price) price ,billid,
billdate
&nb