一条分组查询语句莫名其妙地错误,高手来看一下
表table1(id,acctno,bianh,date),其中有记录:
1,0001,1111,20120102
2,0001,2222,20120103
3,0002,6666,20120102
4,0002,9999,20120104
...
查询出表table1中每个acctno日期最大的那条记录。语句为:
Select id,acctno,bianh,Max(date) As date From table1 Group By acctno
查询结果却为:
2,0001,2222,20120103
4,0002,6666,20120104 //这里编号本应该为9999的,为什么会这样啊?
[解决办法]
Select Max(id),acctno,Max(bianh),Max(date) As date From table1 Group By acctno
[解决办法]
Select a.Id,b.acctno,a.bianh,b.Date From table1 a,;
(Select acctno,Max(Date) As Date From table1 Group By acctno ) b ;
Where a.acctno = b.acctno And a.Date = b.Date
[解决办法]
Select id,acctno,bianh,Max(date) As date From table1 Group By acctno
看看是不是这里的问题.
[解决办法]
你取的是acctno这个组的最大日期 对bianh又没有闲置 所以就取了这个组的随便一个
正确的写法
select * ;
from table1 A ;
where not exists (select 1 from table1 B where A.acctno=B.acctno and A.date<B.date)
[解决办法]
*--- VFP9.0(汉化版) 代码*--- 文件版本:9.0.0.7423create table temp (id int,acctno c(10),bianh I,date c(10))insert into temp values (1,'0001',1111,'20120102')insert into temp values (2,'0001',2222,'20120103')insert into temp values (3,'0002',6666,'20120102')insert into temp values (4,'0002',9999,'20120104')Select id,acctno,BIANH,MAX(date) DATE From temp
[解决办法]
不好意思 我写的是mysql的
[解决办法]
更正5楼代码
Select id,acctno,BIANH,MAX(date) DATE From temp GROUP BY ACCTNO
[解决办法]
Create Table table1 (Id Int,acctno c(10),bianh c(10),Date c(10))Insert Into table1 Values (1,'0001','1111','20120102')Insert Into table1 Values (2,'0001','2222','20120103') && 取此条Insert Into table1 Values (3,'0002','9999','20120102')Insert Into table1 Values (4,'0002','6666','20120104') && 取此条Browse && 看一下原始记录Select * From table1 A Where Not Exists (Select 1 From table1 B Where A.acctno=B.acctno And A.Date<B.Date)*-- 或*-- 下面这句可能需要 vfp9.0 Select a.Id,b.acctno,a.bianh,b.Date From table1 a,(Select acctno,Max(Date) As Date From table1 Group By acctno ) b Where a.acctno = b.acctno And a.Date = b.Date