SQL语句创建一个表作为计数操作的结果?(SQL Statement to create a tab

2019-09-16 18:25发布

比方说,你有一个表像这样

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 statment把浏览器上的报表视图。 嗯,我想这些数据保存到一个SQL。

所以,我需要什么SQL命令插入该报告的结果到表?

假设你已经创建了一个名为表reports本;

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

让我们假设reports表是空的,我们只是想用下面的观点来填充它-用一行代码。 我要问的问题是怎么样?

  terms  count
    a      4
    b      5
    c      1

Answer 1:

就如此容易:

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


Answer 2:

如果表已经存在:

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

如果不:

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


文章来源: SQL Statement to create a table as a result of a count operation?