SQL DB2计算模式

时间:2016-12-29 17:17:54

标签: sql db2 subquery

我使用DB2并有两个表:

用户:

  • ID - key
  • 教育(整数值代表级别)
  • 年龄

付款:

  • 商店
  • 总和
  • 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,错误:在一个已经识别的一个列或表达 条款无效

1 个答案:

答案 0 :(得分:0)

你走了。我已经改为"现代"加入语法。您使用的语法是" old" 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;