星期四, 11月 02, 2023

2002-08-12 如何從資料中取得數字欄位 Top 10 (前 10 名)的資料?


如何從資料中取得數字欄位 Top 10 (前 10 名)的資料?

一般最常從銷售或庫存資料中,取出前 10 名或前幾名作資料分析,AS/400 SQL 只提供
max() 函數取回最大值其語法如下:

select repid, amt from sales2 where amt =       
    (select max(amt) from sales2)

即可取出最佳銷售人員的資料及其銷售額,但要如何取出前幾名的資料呢?

假設您的資料樣本如下:

REPID        AMT 
JLM1      25,922 
NTP2     177,208 
LJS2      15,424 
CRC0     122,730 
HFH1      95,682 
JKS0      76,903 
JLM2      55,088 
JTL4      99,944 
MWS0      12,155 
BRS1      54,673

找第二位的語法如下:

select repid, amt from sales2 as a where 1 = 
  (select count(*) from sales2 as b where    
    b.amt > a.amt)  

這裡是利用 count(*) 筆數來決定,因為只有一筆資料比第二筆資料大,所以查詢結果如下:

REPID        AMT
CRC0     122,730

如果你想要找第三名,只要將 1 改為 2,語法如下:

select repid, amt from sales2 as a where 2 = 
  (select count(*) from sales2 as b where    
    b.amt > a.amt) 

查詢結果如下:

REPID        AMT
JTL4      99,944

如果你想列出前二名,改等號為大於等於,語法如下:

select repid, amt from sales2 as a where 1 >=
  (select count(*) from sales2 as b where    
    b.amt > a.amt)  

查詢結果如下:

REPID        AMT
NTP2     177,208
CRC0     122,730

接著你應該知道如何找前 10 名了,那就是將 1 改為 9 語法如下:


select repid, amt from sales2 as a where 9 >=
  (select count(*) from sales2 as b where    
    b.amt > a.amt)  





沒有留言: