如何在where子句中给出记录计数

时间:2013-03-07 13:30:49

标签: oracle plsql plsqldeveloper

我的代码如下:

select b_id, 
       process_date
  from (select c1.b_id,
               c1.process_date,
               row_number() over(partition by a.a_id 
                                 order by c1.process_date desc) rn
          from table_a a
               inner join 
               table_b b
                 on a.a_id = b.a_id
               inner join 
               table_c c1
                 on b.b_id = c1.b_id
       ) 
 where rn = 1;

如何动态分配rn,即rn = count(rn).Tried并且它是givng错误,表示不是按功能分组

2 个答案:

答案 0 :(得分:1)

您不能在where子句中使用count。使用group by和having。

例如:

SELECT columnname, COUNT(*)   
FROM TableName
GROUP BY columnname
HAVING COUNT(*) = 1

答案 1 :(得分:0)

您可以使用count(*)作为分析函数:

select b_id, 
       process_date
  from (select c1.b_id,
               c1.process_date,
               row_number() over(partition by a.a_id 
                                 order by c1.process_date desc) rn,
               count(*) over()                                  cn
          from table_a a
               inner join 
               table_b b
                 on a.a_id = b.a_id
               inner join 
               table_c c1
                 on b.b_id = c1.b_id
       ) 
 where rn = cn;

如果你只想让最后一个process_date足以对子查询进行排序:

select b_id, 
           process_date
      from (select c1.b_id,
                   c1.process_date,                   
              from table_a a
                   inner join 
                   table_b b
                     on a.a_id = b.a_id
                   inner join 
                   table_c c1
                     on b.b_id = c1.b_id
              order by c1.process_date desc
           ) 
        where rownum = 1;

 where rn = cn;