表结构如下:
品种 数量 销售日期 销售人
ad 1 2010-01-02 admin
ex 2 2010-02-02 admin
ad 3 2010-01-30 admin
ce 1 2010-03-03 admin
......
要求是取出各品种最后销售日期为最后(最大)的那条记录?求SQL查询语句?
品种 数量 销售日期 销售人
ad 1 2010-01-02 admin
ex 2 2010-02-02 admin
ad 3 2010-01-30 admin
ce 1 2010-03-03 admin
......
要求是取出各品种最后销售日期为最后(最大)的那条记录?求SQL查询语句?
解决方案 »
- 数据控件的底层是如何实现的?
- 谁有Delphi控制Outlook的代码!!!
- 如何取得DBGridEh中选择的多行数据..
- 请menggirl(看天上浮云,胜似闲庭信步) 兄、 wfangqian(违反器) 兄、alexzhang00(三角猫(sjcatsoft)) 兄
- “类没有注册”的问题---急用
- clipboard
- ★急★急★急:按F9编译时出现CPU错误提示,用Ctrl+F9编译好后(不提示任何错误),运行程序也没有问题,怎么回事?
- 怎样合并两个二进制文件?
- 改变DBGRID的字段顺序的消息是什么?
- 怎样吧专家分转为可用分啊?
- TreeView读取Data问题
- FtpPutFile函数,有没有连接超时的参数可以设置呢?
1 你肯定要通过GROUP BY 来分组
2 用HAVING来取日期最大值
INSERT INTO @T
select 'ad', 1, '2010-01-02', 'admin' union all
select 'ex', 2, '2010-02-02', 'admin' union all
select 'ad', 3, '2010-01-30', 'admin' union all
select 'ce', 1, '2010-03-03', 'admin' union all
select 'ad', 1, '2010-03-02', 'admin' union all
select 'ex', 2, '2010-02-16', 'admin' union all
select 'ad', 3, '2010-02-12', 'admin' union all
select 'ce', 1, '2010-02-13', 'admin' select * from @T where 品种+cast(日期 as varchar) in
(select 品种+cast(max(日期) as varchar) from @T group by 品种)/* RESUTL
ce 1 2010-03-03 00:00:00.000 admin
ad 1 2010-03-02 00:00:00.000 admin
ex 2 2010-02-16 00:00:00.000 admin
*/
没什么好说的, 楼上的几种方法都行,
但要字段全部显示出来,需要内查询 或用临时表select 品种, max(日期)AS Date INTO #temp1 from table1 group by 品种select * from table1 A
INNER JOIN temp1 B ON A.品种= B.品种 and A.日期=B.Date
SQL语言为:
select t1.*
from table as t1 left outer join table as t2 on t1.type = t2.type
and t1.date < t2.date
group by t1.type, t1.qty, t1.date, t1.usr
having sum(case when t2.type is null then 0 else 1 end) < 1但这种方法的缺陷是:如果有几笔资料都是最后一天的,则都会查出来。
如果只希望出一笔资料,可将table存入一个临时表中,并增加一个identity字段,左连接条件中增加对这个字段的比较条件应该就可以了。注:以上方法应该只适用于SQL Server
select a.* from 原表 a,
(select 品种, max(销售日期) maxdate from 原表 group by 品种) b
where a.品种=b.品种 and a.销售日期=b.maxdate;