日期:2014-05-18  浏览次数:20764 次

求解:关于一个SQL查询不同日期的问题
假如:我有一个表文件。列A为时间、列B为科目、列C为金额。里面的数据金额分别为:

A                                     B                   C
2007-03-01               0311               123456.23
2007-03-04               0311               256235.23
2007-03-15               0411               158925.34
2007-04-03               0311               256254.23
2007-04-15               0411               952452.24
假如我要查询表中0311和0411科目的最后一天的数据,这个SQL语句该如何写?即要查询到0311科目2007-04-03的余额和0411科目2007-04-15的余额


------解决方案--------------------
select * from 表,(select max(A) as A,B from 表 group by B)t
where 表.B=t.B and 表.A=t.A
------解决方案--------------------
select * from table tem1 inner join (select max(A) A ,B from table group by B)tem2 tem2 on tem1.b = tem2.b and tem1.A = tem2.A
------解决方案--------------------
select * from 表
where not exists(select 1 from 表 t where 表.A <t.A and 表.B=t.B)
------解决方案--------------------
drop table 表
go
create table 表(A datetime,B varchar(10),C numeric(20,6))
insert into 表
select '2007-03-01 ', '0311 ',123456.23
union all select '2007-03-04 ', '0311 ',256235.23
union all select '2007-03-15 ', '0411 ',158925.34
union all select '2007-04-03 ', '0311 ',256254.23
union all select '2007-04-15 ', '0411 ',952452.24

select 表.* from 表,(select max(A) as A,B from 表 group by B)t
where 表.B=t.B and 表.A=t.A
/*
A B C
------------------------------------------------------ ---------- ----------------------
2007-04-15 00:00:00.000 0411 952452.240000
2007-04-03 00:00:00.000 0311 256254.230000

(所影响的行数为 2 行)
*/

select * from 表
where not exists(select 1 from 表 t where 表.A <t.A and 表.B=t.B)
/*
A B C
------------------------------------------------------ ---------- ----------------------
2007-04-03 00:00:00.000 0311 256254.230000
2007-04-15 00:00:00.000 0411 952452.240000

(所影响的行数为 2 行)
*/
------解决方案--------------------

declare @a table(A datetime,B varchar(20),c decimal(12,2))
insert into @a select '2007-03-01 ', '0311 ',123456.23
union all select '2007-03-04 ', '0311 ',256235.23
union all select '2007-03-15 ', '0411 ',158925.34
union all select '2007-04-03 ', '0311 ',256254.23
union all select '2007-04-15 ', '0411 ',952452.24
select * from @a


select tem1.* from @a tem1 inner join
(select max(A) A ,B from @a group by B)tem2 on tem1.b = tem2.b and tem1.A = tem2.A