查询roww返回db2中组的第一个元素

时间:2013-04-19 10:18:02

标签: sql db2

假设我有一个填充了下面数据的表,我应该在db2中使用哪个SQL函数或查询来检索具有值为A的FIRST字段FLD_A,值为B的FIRST字段FLD_A的所有行,依此类推?

  ID   FLD_A    FLD_B
  1    A        10
  2    A        20
  3    A        30
  4    B        10
  5    A        20
  6    C        30

我期待下面的表格;我知道按功能GROUP BY but how can I limit the query to return the very first of each group?完成的分组

Essentially I would like to have the information about the very first row where a new value for FLD_A is appearing for the first time?

  ID   FLD_A    FLD_B
  1    A        10
  4    B        10
  6    C        30

2 个答案:

答案 0 :(得分:1)

试试这个在sql中运行

SELECT * FROM Table1 
WHERE ID IN (SELECT MIN(ID) FROM Table1 GROUP BY FLD_A)

答案 1 :(得分:1)

解决此问题的一个好方法是使用窗口函数,特别是row_number()

select t.*
from (select t.*,
             row_number() over (partition by fld_a order by id) as seqnum
      from table1
     ) t
where seqnum = 1;

(假设“first”表示“最小id”。)

如果您使用t.*,则会在输出中添加一个额外的列。您可以只列出要避免的列。