如何在SQL的第一行和最后一行选择一个值?

时间:2017-02-25 03:48:39

标签: sql sql-server

我有一张这样的表:

ID | persid | value1  | value2
---+--------+---------+---------
1  | A      | string1 | string2
2  | A      | string3 | string4
3  | A      | string5 | string6

我需要使用GROUP BY返回类似的内容:

Field1 | field2  |  field3
-------+---------+----------
A      | string1 |  string6 

我使用的是SQL Server 2008, 这可能吗?

4 个答案:

答案 0 :(得分:2)

我会使用条件聚合:

select persid,
       max(case when seqnum_asc = 1 then value1 end) as value1,
       max(case when seqnum_desc = 1 then value2 end) as value2
from (select t.*,
             row_number() over (partition by persid order by id) as seqnum_asc,
             row_number() over (partition by persid order by id desc) as seqnum_desc
      from t
     ) t
group by persid;

答案 1 :(得分:0)

您可以尝试这样的事情:

create table tbl (id int, persid varchar(10), value1 varchar(10), value2 varchar(10));

insert into tbl (id, persid, value1, value2) values (1, 'A', 'string1', 'string2');
insert into tbl (id, persid, value1, value2) values (2, 'A', 'string3', 'string4');
insert into tbl (id, persid, value1, value2) values (3, 'A', 'string5', 'string6');

select tbl.persid, tbl.value1, persmax.value2
from tbl
inner join tbl persmax on persmax.id = (select max(id) from tbl where persid='A')
where tbl.persid='A'
and tbl.id = (select min(id) from tbl where persid='A')

答案 2 :(得分:0)

我认为你可以使用这样的查询:

select top(1) yourTable.persid field1, yourTable.value1 field2, t.value2 field3
from yourTable
  cross join (
    select top(1) value2
    from yourTable
    order by ID desc
  ) t    
order by ID;

答案 3 :(得分:0)

这个怎么样?

select distinct a, b, c from 
    (select mytbl.persid as a, mytbl.value1 as b from mytbl, 
         (select persid, min(id) as id from mytbl group by persid) as t1
              where mytbl.id = t1.id and mytbl.persid = t1.persid) as t2,
    (select mytbl.persid as d, mytbl.value2 as c from mytbl,
         (select persid, max(id) as id from mytbl group by persid) as t3
              where mytbl.id = t3.id and mytbl.persid = t3.persid) as t4
where t2.a = t4.d