0

假设我有一个填充了以下数据的表,我应该在 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
4

2 回答 2

1

试试这个它在sql中工作

SELECT * FROM Table1 
WHERE ID IN (SELECT MIN(ID) FROM Table1 GROUP BY FLD_A)
于 2013-04-19T10:24:31.813 回答
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”的意思是“minimum id”。)

如果您使用t.*,这将在输出中增加一列。您可以只列出要避免这种情况的列。

于 2013-04-19T10:35:58.050 回答