我想找到当周的记录数。 我目前的疑问是:
SELECT Week(Str_to_date(products_options_values, '%m-%d-%Y'), 1) AS order_week,
Year(Str_to_date(products_options_values, '%m-%d-%Y')) AS order_year,
order_active,
Count(op.sub_order_id) AS deliveries
FROM orders_products_attributes opa
LEFT JOIN orders_products op
ON ( opa.orders_products_id = op.orders_products_id )
GROUP BY order_week,
order_year
HAVING order_week = '31'
AND order_year >= '2013'
AND order_active = 0
ORDER BY order_week
它获取deliveries
AS 2
,其中实际上有4条记录,如果我在删除COUNT
和GROUP BY
后运行相同的查询,则会正确显示所有4条记录行。其他周也会出现同样的问题,例如第34周有3条记录,但上面的查询却将其取为4。此外,另一个奇怪的事情是,在GROUP BY
子句中,如果我删除order_week
或order_year
中的任何一个,查询将返回一个空结果集。
知道我做错了吗?
答案 0 :(得分:0)
尝试将所有HAVING条件移至WHERE。另外Count(id)
- 计算ID的UNIQUE值并非全部。如果您需要所有记录计数,请使用COUNT(*)
SELECT Week(Str_to_date(products_options_values, '%m-%d-%Y'), 1) AS order_week,
Year(Str_to_date(products_options_values, '%m-%d-%Y')) AS order_year,
order_active,
Count(op.sub_order_id) AS deliveries
FROM orders_products_attributes opa
LEFT JOIN orders_products op
ON ( opa.orders_products_id = op.orders_products_id )
WHERE order_week = '31'
AND order_year >= '2013'
AND order_active = 0
GROUP BY order_week,
order_year
ORDER BY order_week