我试过看一些类似的例子,例如按日期范围和工作日等分组,但我无法在我的查询中修复它。
根据我的示例数据截图,我只需要返回
Image
和
sum(salesamount)/sum(salescount) for week 1
每周都包含5天(在此示例中为sum(salesamount)/sum(salescount) for week 2.
)。
我的尝试:
wednesday - sunday
我想要的输出是:
select salesstartdate, date_add(salesstartdate, interval 5 day) as gdate,
salesamount, salescount, sum(salesamount)/sum(salescount) as ATV
from testing
group by gdate;
获取Week 1 15.34173913
Week 2 15.80365088
的计算是week 1
获取(3507.1+3639.97+5258.77+8417.04+5994.48)/(285+273+344+478+368)
的计算与上述相同,但日期现在为6月8日至12日。
答案 0 :(得分:1)
您可以使用子查询执行此操作。为了首先对结果集进行正确分组,然后对其执行聚合:
SELECT
concat('WEEK', ' ', weekno) as `Week #`,
MIN(salesstartdate) as startDate,
MAX(salesstartdate) as endDate,
sum(salesamount)/sum(salescount) as ATV
FROM
(
SELECT
salesstartdate,
salesamount,
salescount,
WEEKOFYEAR(salesstartdate) as weekno -- get the week number of the current year
FROM
weekno
WHERE
WEEKDAY(salesstartdate) BETWEEN 2 AND 6 -- get index of week day
) as weeks
GROUP BY
weekno
我在这里使用了2个MySQL函数:
输出:
WEEK 23 | 2016-06-08 | 2016-06-12 | 15.8040
WEEK 24 | 2016-06-16 | 2016-06-19 | 15.9323
并且没有子查询:
SELECT
concat('WEEK', ' ', WEEKOFYEAR(salesstartdate)) as `Week #`,
MIN(salesstartdate) as startDate,
MAX(salesstartdate) as endDate,
sum(salesamount)/sum(salescount) as ATV
FROM
weekno
WHERE
WEEKDAY(salesstartdate) BETWEEN 2 AND 6 -- get index of week day
GROUP BY
WEEKOFYEAR(salesstartdate)
答案 1 :(得分:1)
你可以这样做
select SUBDATE(salesstartdate, WEEKDAY(salesstartdate)) as week_range
, sum(salesamount)/sum(salescount)
from testing
where salesstartdate between SUBDATE(salesstartdate, WEEKDAY(salesstartdate))
and date_add(SUBDATE(salesstartdate, WEEKDAY(salesstartdate)), interval 5 day))
Group by week_range