SQL - 来自多个表的多个聚合

时间:2015-07-28 04:43:36

标签: sql sum aggregate derby

如果已经提出要求,请道歉。我只是这些表

create table sales (
    sale_date timestamp not null,
    amount double precision
}

create table customers (
    event_date timestamp not null,
    cust_cnt integer
}

create table details (
    detail_date timestamp not null,
    type smallint,
    qnty integer
}

示例数据看起来像

sale_date   amount
------------------
1/1/2015    1000
1/2/2015     750
1/3/2015     486

event_date  cust_cnt
--------------------
1/1/2015    10
1/2/2015    15
1/3/2015    12

detail_date type qnty
----------------------
1/1/2015    0    20
1/1/2015    1    18
1/2/2015    0    12
1/2/2015    1     9
1/3/2015    0    31
1/3/2015    1    27

我想要这个输出

total_sales customer_srvd   total_type0_sold    total_type1_sold
-----------------------------------------------------------------
2236           37                    63                  54

我猜,查询看起来像

select sum(amount) as total_sales, 
sum(cust_cnt) as customer_srvd, 
sum(qnty where type=0) as total_type0_sold, 
sum(qnty where type=1) as total_type1_sold 
from sales, customers, details
where sale_date >= 1/1/2015 and  sale_date <= 1/31/2015
and detail_date = sale_date
and event_date = sale_date

如果有人能给我工作榜样,我们将不胜感激。在这一点上,我在德比中尝试它。感谢。

2 个答案:

答案 0 :(得分:0)

我不知道德比db 但在Oracle案例中,以下代码可以正常工作。

select
(
    select sum(amount) from sales where sale_date >= to_date('01/01/2015', 'MM/DD/YYYY') and sale_date <= to_date('01/03/2015', 'MM/DD/YYYY')
) as total_sales,
(
    select sum(cust_cnt) from customers where event_date >= to_date('01/01/2015', 'MM/DD/YYYY') and event_date <= to_date('01/03/2015', 'MM/DD/YYYY')
) as customer_srvd,
(
    select sum(qnty) from details where type=0 and detail_date >= to_date('01/01/2015', 'MM/DD/YYYY') and detail_date <= to_date('01/03/2015', 'MM/DD/YYYY')
) as total_type0_sold,
(
    select sum(qnty) from details where type=1 and detail_date >= to_date('01/01/2015', 'MM/DD/YYYY') and detail_date <= to_date('01/03/2015', 'MM/DD/YYYY')
) as total_type1_sold
from dual;

Run on SQL Fiddle

德比似乎没有双桌 如果在derby db上运行,请将“from dual”替换为“from SYSIBM.SYSDUMMY1”。

答案 1 :(得分:0)

Thanks for you suggestion. Below seems to also provide what I'm looking for, though I'm not sure if this is, performance wise, any better or worse then what was suggested

    select sum(s.amount) as total_sales, sum(c.cust_cnt) as customer_srvd, 
        sum(type0.qnty) as total_type0_sold, sum(type1.qnty) as total_type1_sold
    from sales s
    inner join customers c 
        on date(s.sale_date) = date(c.event_date)
    inner join details type0 
        on date(s.sale_date) = date(type0.detail_date) and type0.type = 0
    inner join details type1 
        on date(s.sale_date) = date(type1.detail_date) and type1.type = 1
    where s.sale_date >= timestamp('2015-01-01 00:00:00') and s.sale_date <= timestamp('2015-01-03 00:00:00')