提问者:小点点

如何为SQLite每年获得x个最佳结果


我的解决方案有问题,我发现以下示例:

(SELECT COUNT(*) FROM person AS b    
WHERE b.group = a.group AND b.age >= a.age) <= 2    
ORDER BY a.group ASC, a.age DESC

(来自:获取每组分组结果的前n条记录)

但是我需要在旧的基础上创建新的列,所以我需要做一些计算,当我试图添加更多的东西时,我会收到错误消息。如果我简单地添加eaquations,就可以了,例如:

(SELECT COUNT(*) FROM person AS b   
WHERE b.group = a.group AND b.age*100 >= a.age*100) <= 2   
ORDER BY a.group ASC, a.age DESC   

但是当我试图重命名我的新专栏时,有太多的AS。

我还尝试使用UNIONALL,但我的SQLite对()不满意。这对我根本不起作用:

(   
  select *     
  from mytable    
  where `year` = 2012   
  order by score*100/50 AS percent desc   
  LIMIT 2   
)   
UNION ALL   
(   
  select *   
  from mytable    
  where `year` = 2013   
  order by score*100/50 AS percent desc   
  LIMIT 2   
)   

“结果:在第1行:
(”附近:语法错误

即使当我在()之前取出SELECT和from时,我也会得到错误消息。

select * from mytable   
(where `year` = 2012   
  order by score*100/50 AS percent desc   
  LIMIT 2)   

UNION ALL   

select * from mytable    
(where `year` = 2013   
  order by score*100/50 AS percent desc   
  LIMIT 2)   

靠近“WHERE”:语法错误

有人能解释一下为什么吗?

编辑

这是数据。

| Person | Year  | Score |   
+--------+-------+-------+
| Bob    | 2013  | 32    |   
| Jill   | 2012  | 34    |   
| Shawn  | 2012  | 42    |   
| Jake   | 2012  | 29    |   
| Paul   | 2013  | 36    |   
| Laura  | 2013  | 39    |

期望结果集:

| Person | Year  | Percent |    
+--------+-------+---------+   
| Shawn  | 2012  | 84      |   
| Jill   | 2012  | 68      |   
| Laura  | 2013  | 78      |   
| Paul   | 2013  | 72      |   
+--------+-------+---------+

其中百分比=分数*100/50


共1个答案

匿名用户

此语法应该工作:

select * 
from (
  select *     
  from mytable    
  where `group` = 1   
  order by age desc   
  LIMIT 2   
)   
UNION ALL   
select * 
from (   
  select *   
  from mytable    
  where `group` = 2   
  order by age desc   
  LIMIT 2   
);

但您也可以使用ROW_NUMBER()执行此操作:

select t.`group`, t.age, ....<rest of the columns from mytable> 
from (
  select *, row_number() over (partition by `group` order by age desc) rn
  from mytable
  where `group` in (1, 2)
) t 
where t.rn <= 2