有表如下:
Name Companyname date Price identity 列
A产品 A公司 2008-05-12 5 1
A产品 A公司 2008-05-30 4 2
B产品 B公司 2008-05-13 5 3
B产品 B公司 2008-05-28 4 4得到的结果如下. 以日期值判断,取最大日期:
name companyname date price
a产品 a公司 2008-05-30 4
b产品 b公司 2008-05-28 4
谢谢.
Name Companyname date Price identity 列
A产品 A公司 2008-05-12 5 1
A产品 A公司 2008-05-30 4 2
B产品 B公司 2008-05-13 5 3
B产品 B公司 2008-05-28 4 4得到的结果如下. 以日期值判断,取最大日期:
name companyname date price
a产品 a公司 2008-05-30 4
b产品 b公司 2008-05-28 4
谢谢.
where not exists(select 1 from tb where a.name=name and a.companyname=companyname and a.date<date)
not exists(select 1 from tb where name =t.name and companyname=t.companyname and date>t.date )
select Name,Companyname,date,Price from tb a
where not exists(select 1 from tb where a.name=name and a.companyname=companyname and a.date <date)
declare @tb table(Name nvarchar(10), Companyname varchar(10), date smalldatetime , Price int, id int)
insert @tb
select N'A产品', 'A公司' , '2008-05-12' , 5 , 1 union all
select N'A产品' , 'A公司', ' 2008-05-30' , 4 , 2 union all
select N'B产品' , 'B公司' , '2008-05-13' , 5 , 3 union all
select N'B产品' ,'B公司' , '2008-05-28' , 4 , 4 select * from @tb as a where not exists(select 1 from @tb where name=a.name and Companyname=a.Companyname and date>a.date )
/*
Name Companyname date Price id
---------- ----------- ------------------------------------------------------ ----------- -----------
A产品 A公司 2008-05-30 00:00:00 4 2
B产品 B公司 2008-05-28 00:00:00 4 4
*/
from 表 a
where
not exists(select 1 from 表 where a.name=name and a.companyname=companyname and date > a.date)
from table as B,
(select max(date) As Date,Name,Companyname
from table
group by Name,Companyname)As A
where A.Name = B.Name
and A.Companyname=B.Companyname
and A.Date=B.date
你看看啊
(select name,company_name,date,price,
row_number()over (partition by name,company_name order by date desc)as u
from table)h
where h.u = 1