在同一字段内有相同的值怎么只显示一次?
例如我的数据表有三个字段:
字段名:ID name date
值: 1 A 2012-1-1
2 B 2012-1-2
2 B 2012-1-3
3 C 2012-1-4
能不能只查出来这样的效果:
字段名:ID name date
值: 1 A 2012-1-1
2 B 2012-1-3
3 C 2012-1-4
就是ID字段内相同的值,只显示时间最新的那一行数据?
[解决办法]
--时间最近,应该是maxselect * from tablename awhere date=(select max(date) from tablename where ID =a.ID )
[解决办法]
select * from tb where not exists(select 1 from tb a where a.date>date and a.id=id and a.name=name)
[解决办法]
create table tb(id int, name varchar(10), [date] date) insert into tb select 1,'A', '2012-1-1' union all select 2 ,'B', '2012-1-2' union all select 2 ,'B', '2012-1-3' union all select 3 ,'C', '2012-1-4' goselect id,name,[date]=MAX([date]) from tb group by id,nameid name date1 A 2012-01-012 B 2012-01-033 C 2012-01-04(3 行受影响)
[解决办法]
use tempdb;/*create table A( ID int not null, name nvarchar(10) not null, [date] nvarchar(10) not null);insert into A values(1,'A','2012-1-1'),(2,'B','2012-1-2'),(2,'B','2012-1-3'),(3,'C','2012-1-4');*/select B.ID,B.name,B.[date]from( SELECT A.ID,A.name,A.[date], row_number() over(partition by A.name order by A.ID,A.[date] desc) as [orderno] FROM A) as Bwhere B.orderno = 1;
[解决办法]
select * from table a where not exists(select 1 from table b where a.id = b.id and a.date < b.date)