2016-09-06 214 views
-1

我拥有的Informix-4GL几行代码,其执行以下操作SQL选择Count使用排序

## 
# 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 

的问题是,如果我含第二个解决方案崩溃在过滤器中的ude order by子句中,我需要它,因为它并不总是按正确的顺序。在这种情况下有没有办法包括一个命令?

+0

计数如何受订单影响?也就是说,如果你省略了ORDER BY子句,它对计数有什么不同?你应该仔细查看你在做什么,因为排序没有意义,尽管[关于它的意见](http://stackoverflow.com/questions/39343776/sql-select-count-using-ordering#comment66019301_39343884) 。至少,对于订单对点票有重要影响的情况,你有一些认真的解释。 –

回答

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 

...要不然正如其他评论者所说,为什么订单很重要?

+0

我将接受这个正确的答案,因为它似乎是最可靠的方法来使用foreach循环 – Trent

0

为什么不直接在第一部分代码中计数?

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

它工作吗?

+0

不,您不能使用idno的订单,因为idno没有出现在结果中 – Trent

+1

据我了解,为什么您需要订单?你在堆积结果以获得计数,所以订单根本不相关,不是吗? – Ethenyl

+0

是的但如果查询返回结果为1,2,3,4,5,6,7,8,9,11,10结果将是错误的 – Trent

0

我相信你的问题在于你在做计数的方式。如果我没有记错的话,你的选择Count将获取一个值而已,我的意思是这一个:

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的计数,则需要将该字段添加到您的第一个select中,并在您需要的顺序之前在末尾添加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" 

请让我知道如果这是你要找的人

+0

它仅用于检索一个值。它需要计算小于10的总行数,唯一的问题是它们在数据库中没有排列顺序 – Trent

+0

您可以添加一个输入数据的例子以及您想得到的结果吗? –