2016-02-12 83 views
1

我有以下SQL查詢返回大多數問題被回答的前五週。這個星期正在被數字返回,但我想要一週的第一個日期而不是數字。在以下查詢中包含來自週數的日期

SELECT Count(*) AS answered, 
    Week(score_datetime) AS week, 
    Year(score_datetime) AS year 
FROM development.score 
WHERE score_datetime IS NOT NULL 
GROUP BY Week(score_datetime) 
ORDER BY answered DESC 
LIMIT 5; 

我的SQL技能是不是最好的,所以我現在得到時momentjs返回從週數的日期。因此,如果有人知道我可以如何在上面的查詢中包含日期以及週數和年份,那麼將非常感激。

+0

如果你選擇t(非聚合)列,那麼一般來說,您也需要將其分組。所以,在這個例子中,YEAR(score_datetime)。 – Strawberry

回答

1

試着這麼做這個:

SELECT Count(*) AS answered, 
    Week(score_datetime) AS week, 
    DATE_ADD(score_datetime, INTERVAL(1-DAYOFWEEK(score_datetime)) DAY) as week_start, 
    Year(score_datetime) AS year 
FROM development.score 
WHERE score_datetime IS NOT NULL 
GROUP BY Week(score_datetime) 
ORDER BY answered DESC 
LIMIT 5; 
1

回答你的具體問題,可以發現:How to convert number of week into date?

因此,基於答案的轉換公式爲:WEEKDAY(DATE_ADD(MAKEDATE(year, 1), INTERVAL Week(score_datetime) WEEK))

將其組合在一起:

SELECT Count(*) AS answered, 
DATE_ADD(MAKEDATE(Year(score_datetime), 1), INTERVAL Week(score_datetime) WEEK) AS week, 
     Year(score_datetime) AS year 
    FROM development.score 
    WHERE score_datetime IS NOT NULL 
    GROUP BY Week(score_datetime) 
    ORDER BY answered DESC 
    LIMIT 5; 
相關問題