Find Name of person in a city with Maximum age - sql

Here the following Query will give the result for Average Age and number of residents in a City. Group BY applied on City and Aggregated functions on residents as Count and Age as AVG.
select city, count(*) as residents, avg(age) as AverageAge
from people
group by city
Similarly I want the Name of the Resident in a City With Maximum Age
select city, name, max(age) as AverageAge
from people
group by city
But this query is not working as name is not there in the Group By clause and neither used as a Aggregated function
Can you please help me in this.

Not the cleanest way, but you can do:
SELECT P1.*
FROM People P1
JOIN
(
SELECT City, MAX(Age) AS Age
FROM People
GROUP BY City
) P2 ON P1.Age = P2.Age AND P1.City = P2.City

UPDATE: When taking execution plans into account, the most performant query I can figure out seems to be the one below; it also seems to give the result that makes the most sense, if there are multiple people of the same (highest) age, they will all be selected;
SELECT P1.*
FROM people p1
LEFT JOIN people p2
ON p1.city=p2.city AND p1.age < p2.age
WHERE p2.age IS NULL
Basically it'll use a simple left join to get all people that don't have anyone older in the same town.
Otherwise, the simplest to read "general" solution would be using a simple subquery to find the max age of anyone in the town and list people in the city of that age. If several people are of the same (highest) age, it will instead return a random one of them;
SELECT city, name, age
FROM people
WHERE age = (SELECT MAX(age) FROM people p WHERE p.city=people.city)
GROUP BY city;
I added the first query to Aaron's SQLfiddle here, as you can see the first query in this post is the only one of the three without a temporary or filesort.

Try
select city, name, max(age) as AverageAge
from people
group by city, name
sql group by query requires all the column names present in the select

You need a sub query, its a very useful technique sutable for a wide range of solutions. When they are needed they are the only effective solution. I always go to this page http://allenbrowne.com/subquery-01.html when I have forgotten the exact synatax I need (worth bookmarking as its not page 1 on google for sub query which it has been in the past) you want the "TOP n records per group" section. Hope this helps

Definition of "maximum age" : there is no individual (in the same city) with a higher age
SELECT pp.*
FROM people pp
WHERE NOT EXISTS (
SELECT *
FROM people px
WHERE px.city = pp.city
AND px.age > pp.age
)
;

Here is the easiest way to do it in my opinion:
SELECT P.city, P.name, P.age as AverageAge
FROM people P
WHERE P.age = (SELECT MAX(age)
FROM people.P2));

Related

Counting the least repeated value and printing the name of that person

I have a database called employees and I want to write an SQL query where you count the least repeating office_id and get the persons name who sits in that office. I can't get it right, will I need to use a subquery for this or is it possible without subquerys? It seems so simple yet, I can't solve it.
id
first_name
office_id
1
Stan
1
2
Danny
1
3
Elle
2
So here I would want to get the name Elle since she has the least reapted office id.
All I have so far is:
SELECT first_name, COUNT(office_id)
FROM employees
GROUP BY first_name;
But all this does is return how many times each name appears in my table. Any ideas? Thanks in advance.
Assuming working with mysql or Postgresql you can try this :
with cte as (
SELECT office_id
FROM employees
GROUP BY office_id
order by count(1) asc
limit 1
)
select e.* from cte c
inner join employees e on e.office_id = c.office_id
Using with will get the least repeating office then with inner join we get all the persons.
You can limit 2 to get the two smallest offices ...
Demo here

How do I get city with highest population in SQL Server (Express Edition)?

So I'm using SQL Server with two columns named City and Population. How do I find the name of the city with the highest population (in syntax)? I've heard SQL Server is a little bit different from MySQL.
Current Code:
Select MAX(Population) from City
In this case, the code is pretty similar between T-SQL and MySQL.
There are other approaches that would work, but this might be the easiest to understand based on the code you've already written.
select
city,
population
from
city
where
population = (
select max(population) from city
)
You may use max(population) over (order by population desc) syntax (do not neglect to alias (here by q) inner query in SQL Server):
SELECT city
FROM
(SELECT MAX(population) OVER (ORDER BY population desc) max_pop, *
FROM city) q
WHERE population = q.max_pop;
SQL Fiddle Demo
You need to find the maximum population in a subquery and then find all cities with that population:
select city
from my_table
where population = (
select max(population) from my_table
)
This query will also give you multiple cities, in the (rare) case where two cities share the maximum population.
You can sort the records by Population in descending order and then pick out the first record only:
SELECT TOP 1 City FROM t
ORDER BY Population DESC

SQL practice troubles for beginner TYT

i've just study SQL for a month and there is many things I'm still cannot get a hold of. Can anyone help me, plz provide the results with some explaination, I need to understand it for future uses. I only list things that I cannot understand.
List the ID of the managers and the total number of employees reporting to each of them. Display the result in descending order of the total number of employees
I can do:
SELECT employeeNumber
FROM employees
WHERE jobTitle LIKE '%Manager%'
UNION
SELECT employeeNumber, COUNT(*)
FROM employees
WHERE reportsTo 'WHICH CONDITION?'
ORDER BY COUNT(*) DESC
Can someone fill in after 'reportTo', I cant find a condition that's working TYT
Display all offices and their counts in each country
I think this mean showing a table with every country and count total number of offices in that country
I can do:
SELECT country, COUNT(*)
FROM offices
GROUP BY country
UNION
SELECT country, officeCode
FROM offices
But the results is not as expected
select
reportsTo,
COUNT(employeeNumber) as numberOfEmployees
from employees
group by reportsTo
Will give you a count of employeeNumbers that report to that reportsTo.
This will not give you the managers where nobody is reporting to, so to do that you would have to make a JOIN:
SELECT
a.employeeNumber AS managerNumber,
COUNT(b.employeeNumber) AS numberOfEmployees
FROM employees AS a
LEFT JOIN employees AS b on (b.reportsTo=a.employeeNumber)
WHERE a.jobTitle LIKE '%Manager%'
GROUP BY a.employeeNumber

Is this sql query correct? If incorrect how can I fix it?

Schema:
Student(studentid,name,age)
Course(coursename,dept)
enroll(studentid,course,grade)
I need to find , for students in each age group find their average grade for courses they have taken for Political Science and History, and return the names of student with max average grade for each age group
My attempt so far is :
select max(grade), age, name
from (
select name, age, grade
from student s, (
select avg(grade) as grade, e.studentid
from enroll e
where dname in ('Political Sciences', 'History')
group by studentid
) as temp
where s.studentid = temp.studentid
) temp1
group by temp1.age;
I want to know if logically it is correct, and not syntactically.
Here's a few tips regarding your query:
Be careful with your table aliases. Make sure that you carry them over to your SELECT
You can only include columns in your SELECT that are being used in your aggregate (GROUP BY). Therefore, you can't GROUP BY temp1.age and SELECT age, name
The logic behind your SQL looks solid to me, so long as "Age" correlates to "Age Group", and does not refer to the individual student's age.

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.