如何计算买家的总数和成本

时间:2016-06-17 16:45:35

标签: database oracle

我想制作一张看起来像这样的表,但我不知道如何解决我的问题,也不确定买家和整体总数。如果可以请帮助

买方|部门|采购|总计

Steve(3)| IT | AWD | $ 70.00

John(2)| Maint | RWD | $ 10.00

Mark(5)|执行| Awd | $ 700.00

但我唯一知道怎么做就是得到一张图表

史蒂夫| IT | AWD | $ 25

史蒂夫| IT | AWD | $ 25

史蒂夫| IT | AWD | $ 25

约翰| MAINT | RWD | $ 7

约翰| maint | RWD | $ 3'/ P>

标志|行政| AWD | $ 100

标志|行政| AWD | $ 100

标志|行政| AWD | $ 100

标志|行政| AWD | $ 300

标志|行政| AWD | $ 100

我的代码看起来像这样:

Start_time      Distance
1/1/2016           2

1 个答案:

答案 0 :(得分:0)

这里的元数据和数据我曾经(我相信)给你你想要的东西(注意:如果没有它会给你一个开始):

create table buyers (buyer varchar2(100), department varchar2(100), procure varchar2(100), cost integer);

insert into buyers values ('Steve', 'IT', 'AWD', 25);
insert into buyers values ('Steve', 'IT', 'AWD', 25);
insert into buyers values ('Steve', 'IT', 'AWD', 25);
insert into buyers values ('John', 'Maint', 'RWD', 7);
insert into buyers values ('John', 'Maint', 'RWD', 3);
insert into buyers values ('Mark', 'Executive', 'AWD', 100);
insert into buyers values ('Mark', 'Executive', 'AWD', 100);
insert into buyers values ('Mark', 'Executive', 'AWD', 100);
insert into buyers values ('Mark', 'Executive', 'AWD', 300);
insert into buyers values ('Mark', 'Executive', 'AWD', 100);

这里是SELECT以获得结果:

select buyer, department, procure, sum(cost) as overall_total
from buyers
group by buyer, department, procure;

以下是您的结果:

enter image description here

如果您希望这些买家在()中计算数字,那么您可以使用的SELECT将是:

select b.buyer || ' (' || a.buyer_cnt || ')' as buyer, department, procure, sum(cost) as overall_total
from buyers b,
     (select count(*) buyer_cnt, buyer
      from buyers
      group by buyer
      ) a
where b.buyer = a.buyer
group by b.buyer || ' (' || a.buyer_cnt || ')', department, procure;

然后你的结果集将如下所示:

enter image description here