Attempting to write a COUNT(*) Query - mysql

Write a query that returns the names of the top five customers who have purchased the most songs from ATunes, ordered by the number of purchases (descending). I must also limit the results to the top 5 as stated.
SELECT P.CustomerID, A.FirstName, A.LastName, P.DateOfPurchase, COUNT(DateOfPurchase) as NumberOfPurchases
ORDER BY NumberOfPurchases DESC, LIMIT 0,5
FROM Purchases as P
JOIN ATunesCostumers as A on (A.CustomerID = P.CustomerID)
GROUP BY CustomerID;
this is what I am trying, and I am getting a syntax error.
When I get rid of the ORDER BY and LIMIT statements I get everything I need for this, other than the limitation and correct ordering. I'm at a loss, does anyone know what I am doing wrong?

Try this:
SELECT P.CustomerID, A.FirstName, A.LastName, P.DateOfPurchase, COUNT(DateOfPurchase) as NumberOfPurchases
FROM Purchases as P
JOIN ATunesCostumers as A on P.CustomerID = A.CustomerID
GROUP BY CustomerID
ORDER BY NumberOfPurchases DESC LIMIT 0,5;

Related

Creating a join where I pull a count from another table

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;

Order by count(*) subquery

Completely new to subqueries, I'm trying to order posts from table showcase by the number of comments they have (in descending order) and not sure how.
SELECT *
FROM showcase
ORDER BY
(select count(*)
from comments)
DESC
If you only need the ids, group by and count rows for each group
select showcase.id
from showcase left join comments on comments.item_id = showcase.id
group by showcase.id
order by count(showcase.id) desc
We need to use group by along with count:
select s.postId, count(c.commentid) as comments
from showcase s join comment c on s.postId = c.postId
group by s.postId
order by comments desc
You can try a join query which is better for query.
SELECT `showcase`.*, count(`comments`.`item_id`) as item_id FROM `showcase`
LEFT JOIN `comments`
ON `showcase`.`id`, `comments`.`item_id`
ORDER BY item_id DESC
Let me know is it work or not.

Select last date and COUNT rows in a JOIN jquery?

I want to select the last inserted date and at the same time I want to select the user-name and count how many times the user-profile is visited.
So I am using this query
SELECT v.visitor_date, i.info_name, count(DISTINCT v.visitor_date) AS counted
FROM profile_visitors v
INNER JOIN profile_info i ON i.info_userId = v.visitor_accountId
ORDER BY v.visitor_date DESC
LIMIT 1
The result of the fiddle is wrong and SHOULD be
2015-07-28 11:05:16 - Testname - 5
Anyone knows what is wrong with the query?
http://sqlfiddle.com/#!9/2814c/1
DISTINCT does NOT give you the first or last record of any group, in fact you cannot guarantee which record DISTINCT will display within a group (nor does this matter by the way). So select MAX visitor date.
Try below query
SELECT MAX( v.visitor_date ) , i.info_name, COUNT( DISTINCT v.visitor_date ) AS counted FROM profile_visitors v INNER JOIN profile_info i ON i.info_userId = v.visitor_accountId ORDER BY v.visitor_date DESC LIMIT 1
You can try it:
SELECT v.visitor_date,
i.info_name,
COUNT(*) AS counted
FROM profile_visitors v
INNER JOIN profile_info i ON i.info_userId = v.visitor_accountId
GROUP BY v.visitor_accountId
ORDER BY v.visitor_date DESC
LIMIT 1

Count repeating names in table

I have two tables: Customer and ParkingTransaction. I want to show the top 10 customers who use the lot most often. 'CustomerKey' in the ParkingTrasaction table is the FK that connects ParkingTransaction to Customer. I have written the following code which counts the most used CustomerKey in the ParkingTransaction table, and it works fine...
SELECT TOP 10 CustomerKey
, count(*) as 'Usage'
FROM ParkingTransaction
GROUP BY CustomerKey
HAVING (count(CustomerKey) > 0)
ORDER BY 'Usage' DESC
This is my output
Output
The problem I am facing is this: I want to pull the FirstName and LastName fields from the Customer table, instead of sorting by just the CustomerKey. I have messed around with JOINS, but haven't come up with a solution yet.
Thanks!
MySQL uses LIMIT not TOP.
SELECT a.FirstName, a.LastName,
COUNT(*) as `Usage`
FROM Customer a
INNER JOIN ParkingTransaction b
ON a.CustomerKey = b.CustomerKey
GROUP BY a.FirstName, a.LastName
ORDER BY `Usage` DESC
LIMIT 10
since the query is using INNER JOIN, HAVING COUNT(*) > 0 is unneccessary in this case.
Here is one way:
SELECT CustomerKey, c.firstname, c.lastname, count(*) as 'Usage'
FROM ParkingTransaction pt join
customer c
on pt.customerkey = c.customerkey
GROUP BY pt.CustomerKey, c.firstname, c.lastname,
ORDER BY 'Usage' DESC
limit 10

Find out AVG column in SQL

I have this php/sql Query:
$result = mysql_query("
SELECT r.item_id, AVG(rating) AS avgrating, count(rating) AS count, i.item, c.category
FROM ratings AS r
LEFT JOIN items AS i
ON r.item_id = i.items_id
INNER JOIN master_cat c
ON c.cat_id = i.cat_id
GROUP BY item_id
ORDER BY avgrating DESC
LIMIT 25;");
When I output this, count is correct, it shows how much votes certain items have received.
I simply want to add a WHERE count >= 10 clause but everything breaks. Obviously, when there are thousands of items, some will get one vote and have 100%. But that is not a good indicator. I want to print out items that have at least 10 votes (or count >= 10)
You should to use having instead where
SELECT
r.item_id, AVG(rating) AS avgrating,
count(rating) AS count, i.item, c.category
FROM
ratings AS r
LEFT JOIN items AS i
ON r.item_id = i.items_id
INNER JOIN master_cat c
ON c.cat_id = i.cat_id
GROUP BY
item_id
HAVING
count >= 10
ORDER BY
avgrating DESC
LIMIT 25;
You can't use a where filter on the results of an aggregate function (count()). where is applied at the row-level, as the DB is deciding whether to include the row or not in the result set - at this point the results of the count aren't available yet.
What you want is a having clause, which is applied as one of the last steps before results are sent to the client, after all the aggregate results have been calculated.
...
GROUP BY item_id
HAVING count > 10
ORDER BY ...
you need to tell it what you want to count
having count(*) > 10