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

SQL - Confusion with INSERT INTO...SELECT and COUNT(*)?

所以我有一个 table 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;

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

当我尝试这样做时,我创建了另一个 table 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

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

尝试使用 MySQL

按函数查看分组
SELECT COUNT(*), IdNumber FROM movement GROUP BY IdNumber;

您甚至可以通过使用 where 子句添加更多条件来使其更漂亮

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

SELECT COUNT(*), IdNumber FROM movement WHERE  IDNumber IN (1,2,3,4) GROUP BY IdNumber;

将结果保存成table -

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

目标 table 将具有列 countIDNumber

怎么样:

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

你没有说它是插入 table 的要求,对吧?

    SELECT idnumber,COUNT(*) 
    FROM movement 
    group by IDNumber;

这是查询和插入:

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
;