I don't know what count(*) is doing when using group by and having.

Asked 2 years ago, Updated 2 years ago, 258 views

I don't know the count(*) when I ran this SQL.

select name from users
group by belong
having count(*)>=2

The tables and data are as follows.

create table users(
  id int,
  name varchar(60),
  belong int
);

insert into users values (1, "A", 102), (2, "B", 103), (3, "C", 102), (4, "D", 105), (5, "E", 103), (6, "F", 102), (7, "G", 104);

SQL has found that group by is followed by a having clause.
So I thought that the select name from users group by Belong was further narrowed down by the having clause.

select name from users group by bellong is as follows:
http://sqlfiddle.com/#!9/c07780/5

This is what happened when I added the having clause.
http://sqlfiddle.com/#!9/c07780/6

How did the count(*)>=2 record be selected from the select name from users group by Belong result?The count(*) in the table retrieved from select name from users group by Belong is only 4, so I don't know how to get to selecting only A and B.

I don't know what COUNT(*) means
I also read the above URL, but I didn't understand and asked you a question.

Can someone teach me?

sql

2022-09-30 22:02

1 Answers

You will find out if you run the query below.

 select name, belong, count(*) from users group by belong

It is difficult to understand because only the name column is displayed as a result of grouping with belong, but belong 102 and 103 meet the conditions of more than two records.


2022-09-30 22:02

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.