表结构如下年度 钱 姓名
2005 101 张山
2005 102 张山
2006 119 张山
2001 102 张山
2006 129 张山
2005 102 李四
2002 119 李四
2005 112 李四
2005 119 李四要求 取出 最近一年 每个人钱最多的记录,最后结果为
2006 129 张山
2005 119 李四
sql 怎么写啊。
2005 101 张山
2005 102 张山
2006 119 张山
2001 102 张山
2006 129 张山
2005 102 李四
2002 119 李四
2005 112 李四
2005 119 李四要求 取出 最近一年 每个人钱最多的记录,最后结果为
2006 129 张山
2005 119 李四
sql 怎么写啊。
解决方案 »
- 求一个交叉表的SQL语名.请帮忙看看.....
- 生日提醒,用SQL怎么写?谢谢大家
- 请问这是什么原因造成的?
- 如果一张表的记录数超过一百万条,查询起来是不是就非常慢呀?
- 如何在sqlserver2008 R2 上创建一个实例
- Windows2000 Profesional 中怎样安装 SQL Server 2000 Profesional 中文版?
- 请教各位SQL高手,一个SQL行号的问题
- 表的合并问题(高手支招阿)
- 因项目时间紧,第一个写出这个存储过程的,经测试成功的立即给100分!!在线等!!【大力帮我】
- SQL对于除不尽的小数问题
- 打补丁SQL Server 2005 SP2时,出现报表服务登陆失败
- 触发器问题
钱=(SELECT max(钱) FROM TB WHERE 年度=T.年度 AND 姓名=T.姓名)
-- Author :fredrickhu(我是小F,向高手学习)
-- Date :2009-10-26 14:10:01
-- Version:
-- Microsoft SQL Server 2005 - 9.00.4035.00 (Intel X86)
-- Nov 24 2008 13:01:59
-- Copyright (c) 1988-2005 Microsoft Corporation
-- Developer Edition on Windows NT 5.2 (Build 3790: Service Pack 1)
--
----------------------------------------------------------------
--> 测试数据:[tb]
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([年度] int,[钱] int,[姓名] varchar(4))
insert [tb]
select 2005,101,'张山' union all
select 2005,102,'张山' union all
select 2006,119,'张山' union all
select 2001,102,'张山' union all
select 2006,129,'张山' union all
select 2005,102,'李四' union all
select 2002,119,'李四' union all
select 2005,112,'李四' union all
select 2005,119,'李四'
--------------开始查询--------------------------
select
*
from
tb t
where
钱=(select max(钱) from tb where 年度=t.年度)
and
(年度=(select max(年度) from tb)
or
年度=(select max(年度)-1 from tb))
----------------结果----------------------------
/*年度 钱 姓名
----------- ----------- ----
2006 129 张山
2005 119 李四(2 行受影响)
*/
create table simadi
(
年度 int ,钱 int, 姓名 varchar(10)
)
insert into simadi
select 2005, 101,'张山' union all
select 2005, 102,'张山'union all
select 2006, 119,'张山'union all
select 2001, 102,'张山'union all
select 2006, 129,'张山'union all
select 2005, 102,'李四'union all
select 2002, 119,'李四'union all
select 2005, 112,'李四'union all
select 2005, 119,'李四'
select 姓名,max(年度),max(钱) from simadi group by 姓名============
姓名
---------- ----------- -----------
李四 2005 119
张山 2006 129(2 行受影响)
select t.* from tb t inner join
(select name,max(moneys) as [money] from tb group by name) as d
on t.name = d.name and t.moneys=d.[money]
--Ken Wong
--测试数据
declare @tb table(年度 char(4), 钱 dec(18,2), 姓名 char(10))
insert into @tb select '2005', 101, '张山' union all
select '2005', 102, '张山' union all
select '2006', 119, '张山' union all
select '2001', 102, '张山' union all
select '2006', 129, '张山' union all
select '2005', 102, '李四' union all
select '2002', 119, '李四' union all
select '2005', 112, '李四' union all
select '2005', 119, '李四'
--查询
select max(年度),max(钱) as 钱,姓名
from @tb
group by 姓名
--结果
---------------
2005 119.00 李四
2006 129.00 张山