2016-12-29 61 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