4

我发现以下代码有助于根据星期五的开始日期创建每周报告。说明说要替换“.$startWeekDay”。带有 4。当我将 '".$startDay."' 设置为 '2013-01-30' 时,出现错误。

此外,我还可以按照我的意愿按天而不是按周收到报告。

SELECT  SUM(cost) AS total, 
    CONCAT(IF(date - INTERVAL 6 day < '".$startDay."', 
            '".$startDay."', 
            IF(WEEKDAY(date - INTERVAL 6 DAY) = ".$startWeekDay.", 
                date - INTERVAL 6 DAY, 
                date - INTERVAL ((WEEKDAY(date) - ".$startWeekDay.")) DAY)),
        ' - ', date) AS week, 
        IF((WEEKDAY(date) - ".$startWeekDay.") >= 0, 
            TO_DAYS(date) - (WEEKDAY(date) - ".$startWeekDay."), 
            TO_DAYS(date) - (7 - (".$startWeekDay." - WEEKDAY(date))))     AS sortDay 
FROM    daily_expense
WHERE   date BETWEEN '".$startDay."' AND '".$endDay."' 
GROUP BY sortDay;

以下代码是我正在使用的

SELECT count(DISTINCT (
UserID)
) AS total, CONCAT(IF(date(LastModified) - INTERVAL 6 day < date(LastModified), 
            date(LastModified), 
            IF(WEEKDAY(date(LastModified) - INTERVAL 6 DAY) = 4, 
                 date(LastModified) - INTERVAL 6 DAY, 
                date(LastModified) - INTERVAL             ((WEEKDAY(date(LastModified)) - 4)) DAY)),
        ' - ',  date(LastModified)) AS week 

FROM  `Purchase` 
WHERE  `OfferingID` =87
AND  `Status` 
IN ( 1, 4 ) 

按周分组

我得到的输出是

total   week
3   2013-01-30 - 2013-01-30
1   2013-01-31 - 2013-01-31
4

1 回答 1

1

我不确定你想如何显示你的星期,上面的 sql 正在尝试显示日期范围。如果这不是必需的,您的查询可能非常简单,您只需将您的时间偏移两天(因为星期五距离一周的自然明星还有两天)并使用 week 函数获取周数。

查询将如下所示:

select count(distinct (UserID)) as total
, year( LastModified + interval 2 day ) as year
, week( LastModified + interval 2 day ) as week_number
FROM  `Purchase` 
WHERE  `OfferingID` =87
AND  `Status` 
IN ( 1, 4 )
group by year, week_number;
于 2013-04-07T02:35:40.813 回答