我有一个查询意味着返回与昨天和去年第一个月之间某段时间内发布的项目相关的各种统计数据。在大多数情况下,以下查询按预期工作。
SELECT DATE_FORMAT(A.ReleaseDate, '%Y-%m') AS FormattedReleaseDate, COUNT(*) AS ReleaseCount, SUM(A.SalesPrice)/COUNT(*) AS MAPAvg, SUM(B.TotalCost)/COUNT(*) AS COGSAvg
FROM item_info A, status B
WHERE A.ReleaseDate BETWEEN '2015-02-01' AND '2016-02-22'
AND A.ListID = B.ListID
GROUP BY MONTH(A.ReleaseDate)
ORDER BY FormattedReleaseDate DESC
这将检索2/1/15和2/22/16之间每个月的指定统计信息。但是,它从本月开始没有返回任何东西。只是为了检查,我运行了这个完全相同的查询,将上面的开始日期替换为2016-02-01
,它检索了我本月预期的结果。出于绝望,我尝试使用item_info
中不同的列,其目的与status
'相同。 TotalCost
列,从而减少了对任何类型的表加入的需求,但我仍然没有从本月获得结果。我知道它存在且属于日期范围。我的第一个查询究竟出了什么问题?我还没有指定结果数量的限制。
答案 0 :(得分:0)
首先,你应该:
group by FormattedReleaseDate
因此,如果在两个不同年份重复月份,则会显示与月份年份不同的行数(并且不会在一个月内将它们堆叠在一起,只会给您12行)。
你也应该尝试:
WHERE STR_TO_DATE(A.ReleaseDate, '%Y-%m-%d')
between STR_TO_DATE('01/02/2015 00:00:00', '%c/%e/%Y %H:%i:%s')
and STR_TO_DATE('22/02/2016 23:59:59', '%c/%e/%Y %H:%i:%s')
只是为了确保您的过滤器更准确。
所以整个查询将是:
SELECT DATE_FORMAT(A.ReleaseDate, '%Y-%m') AS FormattedReleaseDate, COUNT(*) AS ReleaseCount, SUM(A.SalesPrice)/COUNT(*) AS MAPAvg, SUM(B.TotalCost)/COUNT(*) AS COGSAvg
FROM item_info A, status B
WHERE
STR_TO_DATE(A.ReleaseDate, '%Y-%m-%d')
between STR_TO_DATE('01/02/2015 00:00:00', '%c/%e/%Y %H:%i:%s')
and STR_TO_DATE('22/02/2016 23:59:59', '%c/%e/%Y %H:%i:%s')
AND A.ListID = B.ListID
GROUP BY FormattedReleaseDate
ORDER BY FormattedReleaseDate DESC
答案 1 :(得分:0)
我没有正确地对数据进行分组。
SELECT DATE_FORMAT(A.ReleaseDate, '%Y-%m') AS FormattedReleaseDate, COUNT(*) AS ReleaseCount, SUM(A.SalesPrice)/COUNT(*) AS MAPAvg, SUM(B.TotalCost)/COUNT(*) AS COGSAvg
FROM item_info A, inventory_status B
WHERE A.ListID = B.ListID
AND A.ReleaseDate BETWEEN '$startDate' AND '$endDate'
AND A.HideInDealerPricelist = 0
GROUP BY YEAR(A.ReleaseDate), MONTH(A.ReleaseDate)
ORDER BY FormattedReleaseDate DESC