我有一个日期格式和一致价格的行列表(只是一个例子)
date - price
01/01/14 - $5
01/02/14 - $5
01/03/14 - $1
01/10/14 - $1
01/12/14 - $2
我可以使用以下日期别名
成功地按date
进行分组
week(STR_TO_DATE(`date`, '%m/%e/%Y')) AS `date`,
按照MySQL的说法按周分组。
我需要的是按照天的间隔进行分组,这将是从用户界面定义的,即1,2,3,4,5,6天。
我的预期输出是
SELECT
`date`,
SUM`price`,
FROM `table`
GROUP BY date range of 3 days
date - price
01/01/14 - 01/03/14 - $11
01/10/14 - 01/12/14 - $3
提议的想法
编辑 - 由于为每个实例创建了一个新列,因此不起作用。见建议#2
WEEKOFYEAR(STR_TO_DATE(`ship date`, '%m/%e/%Y')) AS `woy`,
WEEKDAY(STR_TO_DATE(`ship date`, '%m/%e/%Y')) AS `wday`,
IF ((SELECT `wday`)='0','range1', '') AS `range`,
IF ((SELECT `wday`)='1','range1', '') AS `range`,
IF ((SELECT `wday`)='2','range1', '') AS `range`,
IF ((SELECT `wday`)='3','range2', '') AS `range`,
IF ((SELECT `wday`)='4','range2', '') AS `range`,
IF ((SELECT `wday`)='5','range2', '') AS `range`,
IF ((SELECT `wday`)='6','range2', '') AS `range`,
提议的想法#2
`Ship Date`,
WEEKOFYEAR(STR_TO_DATE(`ship date`, '%m/%e/%Y')) AS `woy`,
WEEKDAY(STR_TO_DATE(`ship date`, '%m/%e/%Y')) AS `wday`,
CASE
WHEN (SELECT `wday`) = 0 THEN 'range1'
WHEN (SELECT `wday`) = 1 THEN 'range1'
WHEN (SELECT `wday`) = 2 THEN 'range1'
WHEN (SELECT `wday`) = 3 THEN 'range2'
WHEN (SELECT `wday`) = 4 THEN 'range2'
WHEN (SELECT `wday`) = 5 THEN 'range3'
WHEN (SELECT `wday`) = 6 THEN 'range3'
ELSE 'Other'
END AS `range`,
答案 0 :(得分:1)
创建一个额外的列,定义它应该属于哪个“分组”(参见例如In SQL, how can you "group by" in ranges?),也许根据你需要的逻辑使用case语句(参见例如How does MySQL CASE work?)
SELECT GROUPING, SUM(PRICE) FROM
(SELECT
DATE,
PRICE,
{CASE statement for grouping logic} GROUPING
FROM table)
GROUP BY grouping