SELECT *,
DATE(date) AS post_day
FROM notes
WHERE MONTH(date) = '08'
AND userid = '2'
AND YEAR(date) = '2016'
ORDER BY post_day DESC,
timestamp ASC
在这个查询中,我按天分组我的帖子。
我正在努力的是计算每天所有笔记的总字数。有一个单词计数列,其中包含每个帖子的单词计数。是否可以在同一查询中计算此总和,还是需要单独进行?
按表格列:
NoteID UserID Date Note WordCount
答案 0 :(得分:1)
SELECT date, SUM(wordCount) AS monthWordCount
FROM Notes
WHERE userID = 2
AND MONTH(date) = '08'
AND YEAR(date) = '2016'
GROUP BY userID, date
使用上面的代码查看此demo。
如果你想要返回笔记,你也可以做如下的子查询:
SELECT noteID, userID, date, note, wordCount,
(SELECT SUM(wordCount)
FROM Notes
WHERE userID = a.userID
AND date = a.date
GROUP BY userID) AS dayTotalWordCount
FROM Notes a
WHERE a.userID = 102
AND MONTH(date) = '08'
AND YEAR(date) = '2016'
这是使用上述代码的demo。
答案 1 :(得分:0)
首先,不要将select *
与group by
查询一起使用。 select *
对聚合没有意义。 。 。你需要应用聚合函数。
我认为你想要这样的东西:
SELECT DATE(date) as post_day, SUM(WordCount)
FROM notes
WHERE MONTH(date)= '08' AND userid = '2' AND YEAR(date)= '2016'
GROUP BY DATE(date)
ORDER BY post_day DESC, timestamp ASC