SQL查询具有where条件的第二大值

时间:2016-05-21 13:34:31

标签: sql db2 greatest-n-per-group

我有一个带有步骤ID和常驻ID的表。我想写一个查询找到特定居民的第二大步骤id。

在google示例中使用max的查询没有where子句。 试过这个:

<resourceModel>test_mysql4</resourceModel>

表:

SELECT DISTINCT(step_action_id) 
FROM step_table where resident_id =219 
ORDER BY step_action_id DESC limit 2,1;

结果我期待的是856.但我得到以下错误,

Step_Action_id REsident_id
800               218
801               218
911               218
857               218       
856               219
858               219

4 个答案:

答案 0 :(得分:2)

您可以使用ROW_NUMBER()

SELECT step_action_id
FROM (
  SELECT step_action_id, ROW_NUMBER() OVER(ORDER BY step_action_id DESC) AS rn
  FROM (SELECT DISTINCT step_action_id
        FROM step_table 
        WHERE resident_id = 219
     ) AS s
) AS s2
WHERE rn = 2;

LiveDemo

答案 1 :(得分:2)

如果步骤ID不同,您可以使用OFFSETFIRST FIRST 1 ROW ONLY

SELECT step_action_id
FROM step_table 
WHERE resident_id = 219 
ORDER BY step_action_id DESC
OFFSET 1 ROWS
FETCH FIRST 1 ROW ONLY;

如果它们不相同,只需添加GROUP BYSELECT DISTINCT

SELECT step_action_id
FROM step_table 
WHERE resident_id = 219 
GROUP BY step_action_id
ORDER BY step_action_id DESC
OFFSET 1 ROWS
FETCH FIRST 1 ROW ONLY;

答案 2 :(得分:0)

ROW_NUMBER()工作正常,但你也应该知道DB2使用&#34; FETCH FIRST&#34;不限于&#34;限制&#34;返回的行数。所以你可以用子查询得到2,然后反转顺序得到第二个。像这样:

SELECT step_action_id 
FROM (
  SELECT DISTINCT step_action_id 
  FROM step_table 
  WHERE resident_id =219 
  ORDER BY step_action_id DESC
  FETCH FIRST 2 ROWS ONLY
)
ORDER BY step_action_id ASC
FETCH FIRST 1 ROWS ONLY

答案 3 :(得分:0)

感谢大家让我知道解决此问题的各种方法。我使用以下查询解决了它

SELECT max(step_action_id)FROM step_table as p WHERE p.step_action_id&lt; (SELECT max(t.step_action_id)FROM step_table as t,其中t.residentId = 219)和p.residentId = 219&#34 ;;