SQL - 与INSERT INTO混淆... SELECT和COUNT(*)?

时间:2015-06-24 20:22:59

标签: mysql sql select count sql-insert

所以我有一个表Movement,其中有一个名为IDNumber的列。我想要做的是计算ID在该列中每个ID IDNumber中显示的次数

我可以为每个ID单独执行此操作:

SELECT COUNT(*)FROM movement WHERE IDNumber = 379; 
SELECT COUNT(*)FROM movement WHERE IDNumber = 654;
SELECT COUNT(*)FROM movement WHERE IDNumber = 789;
SELECT COUNT(*)FROM movement WHERE IDNumber = 878;

但我想为所有 IDNumber中的ID进行此操作,并且在一个查询中,因为我正在处理的实际数据集很多大。那我该怎么做呢?

当我尝试这样做时,我创建了另一个表IDNumbers,其中列ID列出了Movement中存在的所有不同ID,我这样做了:

INSERT INTO IDCount(`ID`,`Count`)
SELECT n.ID, m.COUNT(*) 
FROM  movement m  
JOIN IDNumbers n
ON n.ID = m.IDNumber 

我希望结果如下:

IDNumber   COUNT 
379        2 
654        1 
789        1 
878        1 

这是 SQL Fiddle

但我知道这完全错了......我该怎么做?任何帮助将不胜感激,谢谢!

4 个答案:

答案 0 :(得分:1)

尝试使用MySQL查看按功能分组

SELECT COUNT(*), IdNumber FROM movement WHERE  IDNumber < 1000 GROUP BY IdNumber;

您甚至可以通过使用where子句

添加更多条件来使其变得更加漂亮
SELECT COUNT(*), IdNumber FROM movement WHERE  IDNumber IN (1,2,3,4) GROUP BY IdNumber;

INSERT INTO target_table SELECT COUNT(*), IdNumber FROM movement GROUP BY IdNumber;

将结果保存到表格中 -

count

目标表将包含IDNumber列和A

答案 1 :(得分:1)

怎么样:

SELECT IDNumber, Count(IDNumber) FROM movement
GROUP BY IDNumber

你没有说要将它插入表中,对吗?

答案 2 :(得分:1)

years <- c(2012,2013,2014,2015)
ppa_holidays <- timeDate(c(USNewYearsDay(year=years), Easter(year=years), USMemorialDay(year=years), 
              USIndependenceDay(year=years), USLaborDay(year=years), USThanksgivingDay(year=years),
              USChristmasDay(year=years)))

答案 3 :(得分:1)

这是查询和插入:

select
    n.id, count(*)
from
    movement m
    join IDNumbers n on m.IDNumber = n.id
group by 
    n.id
;

INSERT INTO IDCount(`ID`,`Count`)
    select
        n.id, count(*)
    from
        movement m
        join IDNumbers n on m.IDNumber = n.id
    group by 
        n.id
;