Объединить два сложных запроса SQL в один - PullRequest
1 голос
/ 30 сентября 2019

У меня есть 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

Конечным результатом будет сумма суммы обоих типов продуктов, сгруппированных по имени клиента каждого месяца определенного года. Я написал запрос, но он работает для 1 типа продукта одновременно. Но я хочу сумму обоих, то есть:

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

Как Джон заказал всего 3 продукта в 2019 году.

Запрос

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

1 Ответ

3 голосов
/ 30 сентября 2019

Использование 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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...