如何计算表中列中具有相同值的行数?

时间:2021-01-18 21:24:56

标签: sql select count

假设我有以下简单的表格:

create table mytable (
    desid bigint not null,
    ancid bigint not null
  );

insert into mytable (ancid,desid) values (1,10);
insert into mytable (ancid,desid) values (1,20);
insert into mytable (ancid,desid) values (1,21);
insert into mytable (ancid,desid) values (1,22);
insert into mytable (ancid,desid) values (2,30);
insert into mytable (ancid,desid) values (3,40);
insert into mytable (ancid,desid) values (3,41);
insert into mytable (ancid,desid) values (3,42);
insert into mytable (ancid,desid) values (3,43);

会打印出以下信息的SQL命令是什么:

4 rows with ancid=1
1 rows with ancid=2
4 rows with ancid=3

1 个答案:

答案 0 :(得分:1)

您可以通过按 ancid 分组来获取信息:

SELECT   ancid, COUNT(*)
FROM     mytable
GROUP BY ancid