简体   繁体   English

在单个查询中获取两个日期范围不同的记录

[英]Get records with difference on 2 different date ranges in single query

I have sales table and have two different date ranges. 我有销售表,并且有两个不同的日期范围。 ie, I have total sales between (2016-12-21 - 2016-12-30) is 100 and for period (2016-12-11 - 2016-12-20) is 85 . 即,我在(2016-12-21 - 2016-12-30) is 100之间的总销售额(2016-12-21 - 2016-12-30) is 100而在期间(2016-12-11 - 2016-12-20) is 85 (2016-12-21 - 2016-12-30) is 100总销售额(2016-12-11 - 2016-12-20) is 85 Now the result I want is 现在我想要的结果是

100 (sales of 2016-12-21 - 2016-12-30), 85 (sales of 2016-12-11 - 2016-12-20), 15 (difference of both periods) through single query. 100 (sales of 2016-12-21 - 2016-12-30), 85 (sales of 2016-12-11 - 2016-12-20), 15 (difference of both periods)通过单个查询查询。

What I am thinking is 我在想的是

select *, (a.sales - b.sales) as diff 
from (select id, sum(sales) as sales from salestable where date >= '2016-12-21' and date <= '2016-12-30') a 
join (select id, sum(sales) as sales from salestable where date >= '2016-12-11' and date <= '2016-12-20') b
on a.id = b.id;

Is there any other better way to do this? 还有其他更好的方法吗?

You can use conditional aggregation: 您可以使用条件聚合:

select sum(case when date >= '2016-12-21' and date <= '2016-12-30' then sales else 0
           end) as sales_a,
       sum(case when date >= '2016-12-11' and date <= '2016-12-20' then sales else 0
           end) as sales_b,
       sum(case when date >= '2016-12-21' and date <= '2016-12-30'
                then sales else 0
                when date >= '2016-12-11' and date <= '2016-12-20'
                then -sales
                else 0
           end) as sales_diff
from salestable;

If you want the overall sum by id (as suggested by your inclusion of id ), then add id to the select and add group by id . 如果您想要按id总和(如包含id ),则将id添加到select并按group by id添加group by id

You can use case to do a conditional sum like this: 您可以使用case进行条件求和,如下所示:

select id,
    sum_21_to_30, 
    sum_11_to_20, 
    sum_21_to_30 - sum_11_to_20 diff
from (select id,
    sum(case when date >= '2016-12-21' and date <= '2016-12-30' then sales else 0 end) sum_21_to_30,
    sum(case when date >= '2016-12-11' and date <= '2016-12-20' then sales else 0 end) sum_11_to_20
from table group by id) t;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM