Below are the two tables, customer and department. I am struggling very hard to get the output.
I want to write the query which shows only the department name which have maximum number of employees.
Answer should be like this ...
Please help me to write the query.
I would suggest using a sub-query, and then selecting from that query. With the outer select, you order by the number of employees and then limit it to 1. This will give you the top department, but also has the flexibility to be modified to give you a list of the x-number of top departments.
SELECT Dep_Name FROM (
SELECT
d.Dep_Name, COUNT(*) AS `count`
FROM
Departments d
JOIN Employees e ON e.Dep_id = d.Dep_id
GROUP BY
d.Dep_id
) AS q
ORDER BY `count` DESC
LIMIT 1
UPDATE
Per a comment by #Dems, you can actually handle this without a sub-query:
SELECT
d.Dep_Name
FROM
Departments d
JOIN Employees e ON e.Dep_id = d.Dep_id
GROUP BY
d.Dep_id
ORDER BY
COUNT(*) DESC
LIMIT 1
SELECT *
FROM
(
SELECT
d.dep_id,
d.dep_name,
count(c.cus_id) cusCount
FROM
cus c,
dep d
WHERE
c.dep_id = d.dep_id
GROUP BY
d.dep_id,d.dep_name
ORDER BY
cusCount desc)
WHERE
ROWNUM = 1;
I created cus & dep tables in Oracle 10g database and tested my code successfully.
What database are you using, and could you post you code.
There error message shows that your "Order by" clause is wrong.
Related
I am trying to get the data for the best 5 customers in a railway reservation system. To get that, I tried getting the max value by summing up their fare every time they make a reservation. Here is the code.
SELECT c. firstName, c.lastName,MAX(r.totalFare) as Fare
FROM customer c, Reservation r, books b
WHERE r.resID = b.resID
AND c.username = b.username
AND r.totalfare < (SELECT sum(r1.totalfare) Revenue
from Reservation r1, for_res f1, customer c1,books b1
where r1.resID = f1.resID
and c1.username = b1.username
and r1.resID = b1.resID
group by c1.username
)
GROUP BY c.firstName, c.lastName, r.totalfare
ORDER BY r.totalfare desc
LIMIT 5;
this throws the error:[21000][1242] Subquery returns more than 1 row
If I remove the group by from the subquery the result is:(its a tabular form)
Jade,Smith,1450
Jade,Smith,725
Jade,Smith,25.5
Monica,Geller,20.1
Rach,Jones,10.53
But that's not what I want, as you can see, I want to add the name 'Jade' with the total fare.
I just don't see the point for the subquery. It seems like you can get the result you want with a sum()
select c.firstname, c.lastname, sum(totalfare) as totalfare
from customer c
inner join books b on b.username = c.username
inner join reservation r on r.resid = b.resid
group by c.username
order by totalfare desc
limit 5
This sums all reservations of each client, and use that information to sort the resulstet. This guarantees one row per customer.
The query assumes that username is the primary key of table customer. If that's not the case, you need to add columns firstname and lastname to the group by clause.
Note that this uses standard joins (with the inner join ... on keywords) rather than old-school, implicit joins (with commas in the from clause: these are legacy syntax, that should not be used in new code.
I want to get the each count of data by combining two tables in MySQL. This is the scenario I have following tables. emp_tab(name, dept_id ) and dept_tab(dept_id, dept_name). I want to write a query to show the number of employees in each department with the department name.
tried code:
SELECT dept_tab.dept_name, number
FROM emp_tab
INNER JOIN dept_tab ON emp_tab.dept_id=dept_tab.dept_id;
My try is not successful. Can you please show me how can I solve this. I am beginner to MySQL
Two things:
You need to use a group by and count function
Your join was joining an invalid table
SELECT dept_tab.dept_name, COUNT(*) as number
FROM emp_tab
INNER JOIN dept_tab ON emp_tab.dept_id=dept_tab.dept_id
GROUP BY dept_tab.dept_name
You can use JOIN and GROUP BY by dept_name to count number of employees.
In your question, what is Customerstable? I assume that is dept_tab?
SELECT
d.dept_name,
COUNT(d.id) AS cnt
FROM
dept_tab d
LEFT JOIN empt_tab e
ON e.dept_id = d.dept_id
GROUP BY d.dept_name ;
I have a table with real estate agent's info and want to pull firstname, fullname, and email from rets_agents.
I want to then get a count of all of their sales from a different table called rets_property_res_mstr.
I created a query that doesn't work yet so I need some help.
SELECT r.firstname, r.fullname, r.email
from rets_agents r
LEFT JOIN rets_property_res_mstr
ON r.email = rets_property_res_mstr.ListAgentEmail
LIMIT 10;
I'm not sure how to get the count in this.
You seem to be looking for aggregation:
SELECT a.firstname, a.fullname, a.email, COUNT(p.ListAgentEmail) cnt
FROM rets_agents a
LEFT JOIN rets_property_res_mstr p ON r.email = p.ListAgentEmail
GROUP BY a.firstname, a.fullname, a.email
ORDER BY ?
LIMIT 10;
Note that, for a LIMIT clause to really make sense, you need a ORDER BY clause so you get a deterministic results (otherwise, it is undefined which records will be shown) - I added that to your query with a question mark that you should replace with the relevant column(s).
I would consider using a CTE for this:
WITH sales as (
SELECT ListAgentEmail, count(*) count_of_sales
FROM rets_property_res_mstr
GROUP BY ListAgentEmail
)
SELECT r.firstname, r.fullname, r.email, count_of_sales
from rets_agents r
LEFT JOIN sales
ON r.email = sales.ListAgentEmail
LIMIT 10;
I am using following query
select
*,
dealer.id As dealerID,
services.id as serviceID
from services
LEFT JOIN dealer
on services.dealer=dealer.id
LEFT JOIN reviews
ON reviews.dealer_id=dealer.id
where services.brand_id = '9' and
services.model_id='107' and
services.petrol > 0
ORDER BY services.total asc ,
AVG(reviews.rating) desc
I have 6 records and it should display 6 records instead its displaying only 1. When i remove AVG(reviews.rating) desc. It display all records.
mysql tables are
services
dealer
brand_id
model_id
petrol
id
total
dealer
id
name
reviews
id
dealer_id
rating
I am not sure where i am doing mistake. If some can help.
avg() is an aggregation function. That is, it takes data from multiple rows and summarizes it.
Without a group by, the query is an aggregation query over all the data. Such a query always returns exactly one row.
Most databases would return an error when you use select *, use an aggregation function, and have no group by. MySQL has a (mis)feature where this syntax is allowed (although on the newest versions, the default settings disallow this).
I'm not sure what you are trying to do, but avg() doesn't make sense in this context. Perhaps this does what you want:
ORDER BY services.total asc, reviews.rating desc
As already mentioned AVG() is aggregate ftn, so I have changed the desc of your order by to include to select the average values.
For future reference:
Providing snippets of raw data also helps. Creating an sql fiddle helps even more
select
*,
dealer.id As dealerID,
services.id as serviceID
from services
LEFT JOIN dealer
on services.dealer=dealer.id
LEFT JOIN reviews
ON reviews.dealer_id=dealer.id
where services.brand_id = '9' and
services.model_id='107' and
services.petrol > 0
ORDER BY services.total asc ,
(SELECT AVG(r2.rating) FROM reviews r2 RIGHT JOIN ON r2.dealer_id=dealer.id) desc
You might try:
SELECT
*,
AVG(c.rating) AS `avg__rating`,
b.id AS dealerID,
a.id AS serviceID
FROM services a
LEFT JOIN dealer b
on a.dealer = b.id
LEFT JOIN reviews c
ON c.dealer_id = b.id
WHERE a.brand_id = '9' and
a.model_id='107' and
a.petrol > 0
GROUP BY a.dealer, a.brand_id, a.model_id, a.petrol, a.id, a.total
ORDER BY a.total asc,
AVG(c.rating) desc
This adds a GROUP BY on the columns in your services table so you will get one row per services/dealer.
I'm messing around with the Sakila sample database in MySQL and I would like to get the top two people who rented the most movies. I've tried a few things and my most recent attempt is:
SELECT c.last_name, Count(r.rental_id)as NumberOfRentals FROM customer c
INNER JOIN rental r ON c.customer_id = r.customer_id
ORDER BY NumberOfRentals DESC
LIMIT 2
It only returns the first name in the database though...
You need a GROUP BY clause. Without having one defined, MySQL will aggregate all the rows which match the given parameters into a single row, instead of aggregating them based on a defined criteria (the last_name in this case).
SELECT c.last_name, Count(r.rental_id)as NumberOfRentals FROM customer c
INNER JOIN rental r ON c.customer_id = r.customer_id
GROUP BY c.last_name
ORDER BY NumberOfRentals DESC
LIMIT 2