数据:
projectid   tastid  no_add   flg1   flg2
1      12     1    0 0
1      12     2    1 0
1      14     1    0 0
1      13     1    0 0
1      13     2    1 0
1      13     3    1 0想得到第二条和最后一条数据(整行),就是每组相同的tastid 中最大的 no_add 并且 flg1 =1
前三列是主键1      12     2    1 0
1      13     3    1 0我现在通过
select Max(NO_ADD) as NO_ADD ,tastID from tbltask
where flg1='1'
and projectid='1'
group by tastID能得到
NO_ADD  tastID 
2 12
3 13
这样我也知道projectid 是可以通过程序取得的,不过得访问两次数据库有没有一个语句就能实现的呢?

解决方案 »

  1.   

    --建表:
    create table test(
    projectid int not null,
    tastid int not null,
    no_add int not null,
    flg1 int   ,
    flg2 int,
    primary key(projectid,tastid,no_add))
    --增加数据:
    INSERT INTO ss VALUES (
    1,
    12,
    1,
    0,
    0);
    INSERT INTO ss VALUES (
    1,
    12,
    2,
    1,
    0);
    INSERT INTO ss VALUES (
    1,
    14,
    1,
    0,
    0);
    INSERT INTO ss VALUES (
    1,
    13,
    1,
    0,
    0);
    INSERT INTO ss VALUES (
    1,
    13,
    2,
    1,
    0);
    INSERT INTO ss VALUES (
    1,
    13,
    3,
    1,
    0);
    --测试语句:
    select a.* from test a,
    (select projectid,tastid,max(no_add) as no_add
    from test where flg1=1 
    group by projectid,tastid) b
    where a.projectid =b.projectid and a.tastid=b.tastid and a.no_add=b.no_add
      

  2.   

    --执行结果:
    projectid   tastid      no_add      flg1        flg2        
    ----------- ----------- ----------- ----------- ----------- 
    1           13          3           1           0
    1           12          2           1           0(所影响的行数为 2 行)
      

  3.   

    增加数据,语法是自动生成的,所以表名成了ss,如果有谁要测试的话,要改为test.