每个员工每周佣金的Oracle SQL

时间:2016-05-11 02:03:16

标签: sql oracle

以下是Oracle 11g数据库中的示例数据,我正在尝试使用SQL查询来返回每位员工每周赚取的佣金。如果员工在一周内没有获得佣金,那么它应该在Commission_earned列中显示0。 (假设周一开始)

SQL>从SALES中选择*;

EMPLID PRODUCT_TYPE          PRODUCTID SALE_AMOUNT COMMISSION_EARNED SALE_DATE
  1001 Desktop                55355251         750                45 02-MAY-16
  1002 Desktop                 2332134         600                30 02-MAY-16
  1001 Laptop                   773643        1200                65 02-MAY-16
  1003 Camera                  5546232         450                25 03-MAY-16
  1002 Printer                  445321         150                15 04-MAY-16
  1001 Printer                  445321         150                15 10-MAY-16
  1003 Camera                  5546232         450                25 10-MAY-16

我正在尝试提供一个sql,它将返回每位员工每周赚取的总佣金。我将不胜感激任何帮助或指示。

WEEKOF EMPLID COMMISSION_EARNED 02-MAY-16 1001 110 02-MAY-16 1002 45 02-MAY-16 1003 25 09-MAY-16 1001 15 09-MAY-16 1002 0 09-MAY-16 1003 25

我想出了下面的sql,但它没有为emplid 1002显示一行,其中commision_earned为0,表示从09-MAY-16开始的一周

SQL> select trunc(sale_date,'IW') WEEKOF,emplid,sum(COMMISSION_EARNED) COMMISSION_EARNED from sales group by trunc(sale_date,'IW'),emplid order by trunc(sale_date,'IW'),emplid;

WEEKOF EMPLID COMMISSION_EARNED 02-MAY-16 1001 110 02-MAY-16 1002 45 02-MAY-16 1003 25 09-MAY-16 1001 15 09-MAY-16 1003 25

1 个答案:

答案 0 :(得分:0)

您可以使用cross join生成所有行,然后使用left join从表中获取信息:

select w.wk, e.emplid,
       coalesce(sum(t.commission_earned), 0) as commission_earned
from (select distinct trunc(weekof, 'IW') as wk from test) w cross join
     (select distinct emplid from test) e left join
     test t
     on t.emplid = e.emplid and trunc(t.weekof, 'IW') = w.wk
group by w.wk, e.emplid
order by w.wk, e.emplid;