简体   繁体   中英

Can anyone please tell me if I am doing this query right?

I have this question in some book I am reading right now..I am a beginner to SQl..learning it..it is not my homework. I am just trying stuff on my own..

Sally wants to query the EMP table and determine how many of the employees live in each of the cities the company has factories in. She writes the following query but it does not work. What is wrong with the way the query is constructed?

SELECT city, COUNT(emp_no) as "Number of Customers"
FROM emp
ORDER BY city
GROUP BY city; 

This is what I did by referring to some other query which had count and group By used in it...I think we also need WHERE clause too in this query..how can i do it??

SELECT empid,count(*) “Employee Total”, city
From emp
Group by city;

Please help..thanks :)

The problem with your first query is that order by should come after group by clause,

SELECT city, COUNT(emp_no) as "Number of Customers"    FROM emp GROUP BY city Order By city;  

The problem with your second query is that you are selecting empid however it's not in Group by list.

Try

SELECT count(*) Employee Total, city From emp Group by city; 

Actually the only thing that's wrong with Sally's query is that the ORDER BY clause needs to be at the end:

SELECT city, COUNT(emp_no) as "Number of Customers"
FROM emp
GROUP BY city
ORDER BY city;

Just switching the GROUP BY and ORDER BY around...

SELECT count(*) as "Employee Total", city
From emp
Group by city;

Using the GROUP BY clause on city will group all of the records with the same city together and the aggregate function COUNT(*) will count how many rows are in each city group.

The problem with what you had before was the empid column in the column select. If you are using GROUP BY you can only have aggregate columns and columns in the GROUP BY clause selected. If you were to add empid to the GROUP BY clause the query would have executed but would not have given you the results you were looking for since it would return each empid and a count of 1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM