繁体   English   中英

将 SQL 的两个复杂查询合并为单个

[英]Merge two complex queries of SQL into single

我有 3 张表,其中一张是客户的 product_type_1 和 product_type_2。

顾客

| id | name  |
|----|-------|
| 1  | Alex  |
| 2  | John  |
| 3  | Ahmad |
| 4  | Sam   |

product_type_1

| id | order_by  | Date
|----|--------------|-------|
| 1  |------ 1 ---- | 2019-03-01
| 2  |------ 2 ----| 2019-03-02
| 3  |------ 2 ----| 2019-03-03
| 4  |------ 3  ----| 2019-03-04

product_type_2

| id | order_by  | Date
|----|--------------|-------|
| 1  |------ 1 ---- | 2019-03-01
| 2  |------ 3 ----| 2019-03-02
| 3  |------ 3 ----| 2019-03-03
| 4  |------ 2  ----| 2019-03-04

最终的 output 将是按特定年份每个月的客户名称分组的两种产品类型的总和。 我已经编写了查询,但它一次适用于 1 种产品类型。 但我想要两者的总和,即:

Customer | Jan | Feb | Mar .... Total<br>
:------------------------------------------------------:
John  ------   |  0  -- |--- 0   |--- 3  ......  3

正如约翰在 2019 年共订购了 3 种产品。

查询是

select c.name,
               sum( month(o.order_date) = 1 and year(o.order_date)=2010) as Jan,
               sum( month(o.order_date) = 2 and year(o.order_date)=2010) as Feb,
               sum( month(o.order_date) = 3 and year(o.order_date)=2010) as Mar,
               sum( month(o.order_date) = 4 and year(o.order_date)=2010) as Apr,
               sum( month(o.order_date) = 5 and year(o.order_date)=2010) as May,
               sum( month(o.order_date) = 6 and year(o.order_date)=2010) as Jun,
               sum( month(o.order_date) = 7 and year(o.order_date)=2010) as Jul,
               sum( month(o.order_date) = 8 and year(o.order_date)=2010) as Aug,
               sum( month(o.order_date) = 9 and year(o.order_date)=2010) as Sep,
               sum( month(o.order_date) = 10 and year(o.order_date)=2010) as Oct,
               sum( month(o.order_date) = 11 and year(o.order_date)=2010) as Nov,
               sum( month(o.order_date) = 12 and year(o.order_date)=2010) as December,
               count(*) as total
        from customers c join
          (
          select order_by as cID, order_price , order_date
             from orders where year(order_date)=2010
          ) o
        on o.cID = c.id and o.order_price > 0
        group by c.name
        order by total desc

使用union all和聚合:

select c.id, c.name,
       sum( month(o.order_date) = 1 and year(o.order_date)=2010) as Jan,
       . . .
from customers c left join
     ((select order_by, date
       from product_type_1
      ) union all
      (select order_by, date
       from product_type_2
      ) 
     ) p12
     on p12.order_by = c.id
group by c.id, c.name

暂无
暂无

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

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