如何获取表中位置元素的信息?

时间:2015-05-12 10:43:54

标签: postgresql

我有疑问:

Select * from mytable order by 'date'

结果:

   date    | item_id | user_id | some_data
------------------------------------------
2015-01-01 |       1 |       1 | null
2015-01-01 |       1 |       1 | null
2015-01-02 |       1 |       1 | null
2015-01-03 |       1 |       1 | null
2015-01-03 |       1 |       2 | null
2015-01-04 |       1 |       1 | null
2015-01-05 |       1 |       2 | null

我想得到第一行的位置,其中user_id = 2.在这个例子中它是5.怎么做?

2 个答案:

答案 0 :(得分:2)

select pos_overall
from (
  select user_id, 
         row_number() over (order by "date") as pos_overall,
         row_number() over (partition by user_id order by "date") as user_pos
  from mytable
) t
where user_id = 2
  and user_pos = 1

答案 1 :(得分:1)

您可以使用row_number()函数按日期,user_id的顺序对行进行编号,然后选择最小值:

select min(rn) 
from (
  select 
    user_id, row_number() over (order by date, user_id) as rn 
  from mytable 
) x
where user_id = 2;

如果item_id可以更改,您可能希望在派生表中的row_number函数的order by子句中包含它。