SQL使用排序选择计数

时间:2016-09-06 08:09:06

标签: sql informix

我有几行Informix-4GL代码执行以下操作

##
# prepare sql
##

let lv_sql = " select table.idno from table ",
             " where table.status != 'X' ",
             " and table.idno <= 10 ",
             " order by table.idno "
prepare table_sel from lv_sql
declare table_cur cursor for table_sel

##
# loop through results and count them
##

let count = 0

foreach table_cur into ti_num
   let count = count + 1
end foreach

display count

所以我在正确的顺序序列中得到特定表中小于10的行总数,但我需要一个foreach循环来计算总数

我有第二种做法,我更喜欢

##
# prepare sql
##

let lv_sql = " select count(table.idno) from table ",
             " where table.idno in ( ",
             "    select table.idno from table "
             "    where table.status != 'X' ",
             "    and table.idno <= 10 ",
             " ) "
prepare table_sel from lv_sql

##
# just get result
##

execute table_sel into count

display count

问题是,如果我在过滤器中的where中包含order by子句并且我需要它,那么第二个解决方案会崩溃,因为它并不总是按正确的顺序排列。有没有办法在这样的情况下包含订单?

3 个答案:

答案 0 :(得分:0)

为什么不直接在代码的第一部分计算?

let lv_sql = " select count(table.idno) from table ",
         " where table.status != 'X' ",
         " and table.idno <= 10 ",
         " order by table.idno "

有效吗?

答案 1 :(得分:0)

我相信你的问题在于你计算的方式。如果我没有弄错,你的选择计数只会检索一个值,我的意思是这个:

let lv_sql = " select count(table.idno) from table ",
             " where table.idno in ( ",
             "    select table.idno from table "
             "    where table.status != 'X' ",
             "    and table.idno <= 10 ",
             " ) "
因此,没有必要订购。如果您需要表id的引用以及每个Id的计数,您需要将该字段添加到第一个选择中,并在您需要的订单之前添加group by子句,如下所示:

let lv_sql = " select table.idno, count(table.idno) as counting from table ",
             " where table.idno in ( ",
             "    select table.idno from table "
             "    where table.status != 'X' ",
             "    and table.idno <= 10 ",
             " ) group by table.idno order by counting"

如果您正在寻找

,请告诉我

答案 2 :(得分:0)

我一直在重读这个问题并认为答案是......

let lv_sql = " select table.idno, count(*) ",
             " from table ",
             " where table.status != 'X' ",
             " and table.idno <= 10 ",
             " order by table.idno "
prepare table_sel from lv_sql
declare table_cur cursor for table_sel

foreach table_cur into l_idno, l_count
    ...
end foreach

...或者其他评论者说过,为什么订单很重要?