Select * from 销售记录表 a
where 销售日期=(select max(销售日期) from 销售记录表 where 商品ID=a.商品ID)or:
Select * from 销售记录表 a
where 销售日期=(select top 1 销售日期 from 销售记录表 where 商品ID=a.商品ID order by 销售日期 desc)
where 销售日期=(select max(销售日期) from 销售记录表 where 商品ID=a.商品ID)or:
Select * from 销售记录表 a
where 销售日期=(select top 1 销售日期 from 销售记录表 where 商品ID=a.商品ID order by 销售日期 desc)
商品销售表
===============================
商品ID 销售日期 数量 单价
001 2004-6-10 7 10
001 2004-6-11 8 10
001 2004-6-12 10 10
002 2004-6-13 11 10
003 2004-6-9 15 9
003 2004-6-10 16 11
003 2004-6-12 13 10想获得结果:
===============================
商品ID 销售日期 数量 单价
001 2004-6-12 10 10
002 2004-6-13 11 10
003 2004-6-12 13 10这个SQL语句要如何写??
tx1icenhe(冒牌马可 V0.1)
的可以.支持...
select * into 销售记录表1 from 销售记录表
//找出最后的一笔记录
select 销售记录表1.id,date into 销售记录表2 from 销售记录表1
group by id
having max(date)//比较查找
Select 销售记录表。商品ID,销售记录表。(销售日期) as 销售日期,销售记录表。max(数量) as 数量
from 销售记录表,销售记录表1
where 销售记录表。id=销售记录表2.id and 销售记录表.date=销售记录表2.date商品ID=id, 销售日期 =date//没软件环境,仅供参考。
from 销售记录表 a
where not exists (select 1
from 销售记录表
where 商品ID = a.商品ID
and 销售日期 > a.销售日期
)
insert 销售记录表 values( '001','2004-6-10',7,10)
insert 销售记录表 values( '001','2004-6-11',8,10)
insert 销售记录表 values( '001','2004-6-12',10,10)
Select 商品ID,销售日期=convert(varchar(10),销售日期,120),数量,单价
from 销售记录表 a
where not exists (select 1
from 销售记录表
where 商品ID = a.商品ID
and 销售日期 > a.销售日期
)drop table 销售记录表----运行结果商品ID 销售日期 数量 单价
001 2004-06-12 10 10
from 销售记录表 b
, (Select top 1 商品ID,max(销售日期 ) as 销售日期
from 销售记录表
group by 商品ID desc) as a
where
b.商品ID=a.商品ID
and b.销售日期=a.销售日期
以下是微软工程师给我的回复:
下面是我测试的语句,供您参考,他们在我的机器上成功通过
----建立数据库
CREATE TABLE [dbo].[TABLE1] (
[商品ID] [int] NOT NULL ,
[销售日期] [datetime] NOT NULL ,
[数量] [int] NOT NULL ,
[单价] [int] NOT NULL
) ON [PRIMARY]
GO
----插入示例数据
insert into table1 values ('001','2004-6-10',7,10)
insert into table1 values ('001','2004-6-10',7,10)
insert into table1 values ('001','2004-6-11',8,10)
insert into table1 values ('001','2004-6-12',10,10)
insert into table1 values ('002','2004-6-13',11,10)
insert into table1 values ('003','2004-6-9',15,9)
insert into table1 values ('003','2004-6-10',16,11)
insert into table1 values ('003','2004-6-12',13,10)
GO
----通过Inner Join来查询
select t1.* from table1 as t1 inner join
(select t2.[商品ID] ,max(t2.[销售日期]) as [销售日期] from Table1 as t2 group by t2.[商品ID]) as t3
on (t1.[商品ID] = t3.[商品ID] AND t1.[销售日期] = t3.[销售日期])
order by t1.[商品ID]