【问题标题】:SQL Statement to create a table as a result of a count operation?作为计数操作的结果创建表的 SQL 语句?
【发布时间】:2012-04-25 23:43:30
【问题描述】:

假设你有一张这样的桌子

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

【问题讨论】:

标签: mysql sql count recordset


【解决方案1】:

就这么简单:

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

【讨论】:

  • 一想到以特定顺序将数据推送到表中,我就感到畏缩。主要是因为不能保证“默认”以该顺序 out 获取数据 - 它需要在选择结束时使用 ORDER BY 语句。
【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-04
    • 1970-01-01
    • 1970-01-01
    • 2021-10-31
    • 1970-01-01
    • 2015-04-05
    相关资源
    最近更新 更多