2016-12-29 60 views
1

我使用DB2和有兩個表:SQL DB2計算模式

用戶:

  • ID - 關鍵
  • 教育(整數值表示級)
  • 年齡

付款方式:

  • 總和
  • ID - 外鍵

我要計算教育的統計模式,每家商店,現在我想類似的東西: 1)計算店X模式:

select u.education    
    from users u, payments p 
    where u.id = p.id AND    
    p.shop = 'X'  
    group by u.education order by count(*) desc 
    fetch first 1 rows only;      

此查詢工作正常

2)計算教育的模式,每店:

select p.Shop as Shop,      
    avg(u.age) as AvgAge,          
    (select u1.education           
     from users u1          
     where u1.id = p.id         
     group by u1.education           
     order by count(*) desc           
     fetch first 1 rows only) as ModeEdu        
    from users u, payments p      
    where u.id = p.id          
    group by p.Shop;       

這個查詢給出了一個錯誤:

SQLCODE = -119,ERROR:確定了具有 子句中的列或表達式無效

+0

爲什麼平均年齡包含在查詢中?你能顯示一些樣本數據和預期的輸出嗎? –

+0

@vkp我包括年齡,因爲我也試圖獲得一些關於用戶的其他信息,但在選擇教育模式方面存在問題。 – MRMKR

+0

@vkp你想要看什麼樣品? – MRMKR

回答

0

在這裏你去。我已經更改爲「現代」連接語法。你20年前使用的語法是「老」。我強烈推薦使用新的語法。

WITH eduCount AS 
(
    select u1.id, u1.education, count(*) as c 
    from users u1 
    group by u1.id u1.education           
), byUser AS 
( 
    select id, education, c, 
    ROW_NUMBER() OVER (PARTITION BY id, education ORDER BY c DESC) AS RN 
    from eduCount 
) 
select p.Shop as Shop,      
    avg(u.age) as AvgAge,          
    max(byUser.education) as ModeEdu 
from users u 
join payments p on u.id = p.id 
left join byUser on byUser.id = u1.id AND rn = 1 
group by p.Shop;   
+0

我使用vista tn3270和spufi來運行查詢,它給了我錯誤:SQLCODE = -104,錯誤:ILLEGAL SYMBOL「ROW_NUMBER」。 可能是合法的一些符號是:從INTO – MRMKR

+0

@MRMKR - 我現在有一個排字錯誤 – Hogan

+0

我在eduCount中遇到了問題,使用eduCount AS(選擇u1.id,u1.education,count(*)as c從用戶u1組通過u1.id,u1.education)提供一個錯誤:U1.ID不在其中使用的地方 – MRMKR