2012-04-25 68 views
0

假設你有一個表像這樣作爲計數操作的結果創建表的SQL語句?

id terms  
1 a  
2 c  
3 a  
4 b  
5 b  
6 a  
7 a 
8 b 
9 b 
10 b   

,你想用這樣的報告結束了;

terms count 
a  4 
b  5 
c  1 

所以,你在第一臺

SELECT terms, COUNT(id) AS count 
    FROM table 
GROUP BY terms 
ORDER BY terms DESC 

到目前爲止一切順利運行此。

但上面的SQL語句在瀏覽器上放置了報表視圖。那麼,我想將這些數據保存到SQL中。

那麼,我需要什麼SQL命令將該報告的結果插入到表中?

假設您已經創建了一個名爲reports的表格,

create table reports (terms varchar(500), count (int)) 

讓我們假設reports表是空的,我們只是想用下面的觀點來填充它 - 用一行代碼。我問的問題是如何?

terms count 
    a  4 
    b  5 
    c  1 
+0

http://dev.mysql.com /doc/refman/5.0/en/insert-select.html – 2012-04-25 23:46:42

回答

4

就這麼簡單:

INSERT INTO reports 
SELECT terms, COUNT(id) AS count 
FROM table 
GROUP BY terms 
ORDER BY terms DESC 
+1

我對這個想法感到畏懼按特定順序將數據推送到表中。主要是因爲您不能保證按默認順序獲取數據_out_ - 它需要在選擇結束時使用'ORDER BY'語句。 – 2012-04-25 23:50:50

1

如果表已經存在:

Insert reports 
SELECT terms, COUNT(*) AS count 
FROM table 
GROUP BY terms 

如果不是:

SELECT terms, COUNT(*) AS count 
into reports 
FROM table 
GROUP BY terms