Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 将2个分支机构的3个月销售报告汇总为每月的前3名产品_Sql_Oracle_Querying - Fatal编程技术网

Sql 将2个分支机构的3个月销售报告汇总为每月的前3名产品

Sql 将2个分支机构的3个月销售报告汇总为每月的前3名产品,sql,oracle,querying,Sql,Oracle,Querying,我有下面的报告表 m = month, pid = product_id, bid = branch_id, s = sales m pid bid s -------------------------- 1 1 1 20 1 3 1 11 1 2 1 14 1 4 1 16 1 5 1

我有下面的报告表

m = month,
pid = product_id,
bid = branch_id,
s = sales

m       pid     bid     s
--------------------------
1       1       1       20
1       3       1       11
1       2       1       14
1       4       1       16
1       5       1       31
1       1       2       30
1       3       2       10
1       2       2       24
1       4       2       17
1       5       2       41
2       3       1       43
2       5       1       21
2       4       1       10
2       1       1       5
2       2       1       12
2       3       2       22
2       5       2       10
2       4       2       5
2       1       2       4
2       2       2       10
3       3       1       21
3       5       1       10
3       4       1       44
3       1       1       4
3       2       1       14
3       3       2       10
3       5       2       5
3       4       2       6
3       1       2       7
3       2       2       10
我想要这张销售表的摘要 通过显示所有分支机构产品的前三名销售额。 大概是这样的:

m       pid     total
---------------------
1       5       72
1       1       50
1       4       33
2       3       65
2       5       31
2       2       22
3       4       50
3       3       31
3       2       24
因此,在第1个月,产品5的总销售额最高,为72台,其次是产品1,为50台。。等等如果我能把它们分为不同的表格,每个月会更好

到目前为止,我能做的是做一个1个月的总结,展示整个事情,而不是前3名

select pid, sum(s)
from report
where m = 1
group by pid
order by sum(s);

非常感谢

大多数数据库支持ANSI标准窗口函数。您可以使用row_number执行您想要的操作:


你使用的是什么数据库?大学labHi的oracle 11g谢谢,它可以工作,我做了一些修改:1在第2行末尾添加一个,可能是oracle的要求。2删除最后一行上的pid,只需按m,s desc命令即可;到目前为止,这里的输出看起来还不错。你怎么认为?
select m, pid, s
from (select r.m, r.pid, sum(s) as s,
             row_number() over (partition by m order by sum(s) desc) as seqnum
      from report r
      group by r.m, r.pid
     ) r
where seqnum <= 3
order by m, s desc;