简体   繁体   中英

MySQL GROUP BY with subquery (ies)

I'm trying to count the number of orders in a date range, grouping by date but also counting some other records which occurred on the same date.

I have a query which looks something like this:

SELECT 
order_date,
DATE_FORMAT(order_date,'%W') AS day, 
DATE_FORMAT(order_date,'%d-%m-%Y') AS orderdate, 
COUNT(orderID) As orders, 
a.something AS something
b.something AS something_else,
a.something + b.something AS total_somethings
FROM orders,
(SELECT COUNT(*) AS something FROM other_table) AS a,
(SELECT COUNT(*) AS something FROM another_table) AS b,
GROUP BY order_date 
HAVING order_date >= '2014-01-01' AND order_date <= '2014-01-31' 
ORDER BY order_date ASC

It works OK but obviously, the subqueries count every single row. The tables 'other_table' and 'another_table' both have date fields which I would like to use to limit the results for each row.

I tried changing the subqueries to something like :

(SELECT COUNT(*) AS something FROM other_table WHERE date_field = order_date) AS a,

but it's still counting every single row.

Any advice appreciated.

Thanks

In the following query, I grouped the date_field in other_table and another_table tables. Then, I joined with the orders table using the date_field . Does the following query work for you?

SELECT 
order_date,
DATE_FORMAT(order_date,'%W') AS day, 
DATE_FORMAT(order_date,'%d-%m-%Y') AS orderdate, 
COUNT(orderID) As orders, 
a.something AS something
b.something AS something_else,
a.something + b.something AS total_somethings
FROM orders,
(SELECT date_field, COUNT(*) AS something FROM other_table GROUP BY date_field) AS a,
(SELECT date_field, COUNT(*) AS something FROM another_table GROUP BY date_field) AS b
WHERE order_date >= '2014-01-01' AND order_date <= '2014-01-31' 
AND order_date = a.date_field AND order_date = b.date_field
GROUP BY order_date 
ORDER BY order_date ASC;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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