G
G
gofree2020-04-29 17:29:21
MySQL
gofree, 2020-04-29 17:29:21

How to merge query in MySQL?

Hello. I'm making a selection from the sales table in order to collect statistics for 12 months, I can't figure out how to combine requests into one.

SELECT
SUM(`price`) as `sales`,
SUM(`seller_salary`) as `salary`,
DATE_FORMAT(`putdate`, '%Y-%m') as period
FROM `ms_sales`
WHERE `putdate` >= DATE_FORMAT(CURRENT_DATE - INTERVAL 11 MONTH, '%Y-%m-01')
GROUP BY period

SELECT
COUNT(`category_id`) as `m`,
DATE_FORMAT(`putdate`, '%Y-%m') as period
FROM `ms_sales`
WHERE `putdate` >= DATE_FORMAT(CURRENT_DATE - INTERVAL 11 MONTH, '%Y-%m-01') AND `category_id` = '1'
GROUP BY period

SELECT
COUNT(`category_id`) as `t`,
DATE_FORMAT(`putdate`, '%Y-%m') as period
FROM `ms_sales`
WHERE `putdate` >= DATE_FORMAT(CURRENT_DATE - INTERVAL 11 MONTH, '%Y-%m-01') AND `category_id` = '2' OR `category_id` = '3'
GROUP BY period

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
galaxy, 2020-04-29
@gofree

First, there are problems with parentheses:

DATE_FORMAT(CURRENT_DATE - INTERVAL 11 MONTH, '%Y-%m-01' AND `category_id` = '1')

And here is a bit too AND, for my taste:
AND `category_id` = '2' AND `category_id` = '3'

About the merger:
SELECT
SUM(`price`) as `sales`,
SUM(`seller_salary`) as `salary`,
COUNT(CASE WHEN `category_id` = '1' THEN 1 END) as cat1_count,
COUNT(CASE WHEN `category_id` = '2' OR `category_id` = '3'  THEN 1 END) as cat23_count,
DATE_FORMAT(`putdate`, '%Y-%m') as period
FROM `ms_sales`
WHERE `putdate` >= DATE_FORMAT(CURRENT_DATE - INTERVAL 11 MONTH, '%Y-%m-01')
GROUP BY period

I dealt with mysql for a long time, I don’t know if CASE works there as expected.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question