2016-09-06 70 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

您可以添加一個輸入數據的例子以及您想得到的結果嗎? –