我有下表:
Article ID, Views, Date
11, 55, 2013-01-01
12, 341, 2013-01-01
11, 432, 2013-01-02
我想创建一个新表,它只包含Views字段中每篇文章的总和(即:)
Article ID, Views
11, 487
12, 341
我是否必须编写一个单独执行每个脚本的脚本,或者是否有一个mysql语句?
答案 0 :(得分:1)
Insert into Table2 (`Article Id`, Views)
Select `Article ID`, SUM(Views)
FROM TABLE1 GROUP BY `Article ID`;
<强> Fiddle 强>
答案 1 :(得分:0)
您只需一个简单的查询
即可INSERT INTO SumTable (ArticleId, Views)
SELECT ArticleId, SUM(Views) FROM SourceTable GROUP BY ArticleId
如果您还想创建一个新表,可以按照此处的描述组合CREATE和SELECT: http://dev.mysql.com/doc/refman/5.0/en/create-table-select.html
示例:
CREATE TABLE SumTable SELECT ArticleId, SUM(Views) FROM SourceTable GROUP BY ArticleId