我正在尝试计算日期范围内的订单数量,按日期分组,但也计算在同一日期发生的其他记录。
我的查询看起来像这样:
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
它工作正常,但很明显,子查询计算每一行。表'other_table'和'another_table'都有日期字段,我想用它来限制每行的结果。
我尝试将子查询更改为:
(SELECT COUNT(*) AS something FROM other_table WHERE date_field = order_date) AS a,
但它仍在计算每一行。
任何建议表示赞赏。
由于
答案 0 :(得分:1)
在以下查询中,我将date_field
分组在other_table
和another_table
表中。然后,我使用orders
加入了date_field
表。以下查询是否适合您?
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;