mySQL query issue -- homework - mysql

I need some help with one of the questions from my homework, Ive been trying for about an hour now and cant get it to run.
List the customers that bought more items than the average number of items per customer
The tables are as follows:
Customer(Cnum, CustomerName, Address)
Item(Inum, ItemName, Manufacturer, Year)
Bought(Cnum, Inum, Date, Quantity)
Prefer(Inum, Cnum)
The best i could figure out was that it needs to be the total Quantity per Customer compared to the overall average of the Quantity. I've tried various forms of this query:
SELECT Cnum
FROM Bought
WHERE
(
SELECT Cnum, SUM(Quantity)
FROM Bought
GROUP BY Cnum;
) >
(
SELECT AVG(Quantity)
FROM Bought
);
But it returns an error -- (phpMyAdmin isnt telling me what the problem is, just failing to execute and going to no connection page, which means error in my query)
I have also tried to return the higher SUM with:
SELECT SUM(Quantity)
FROM Bought
WHERE SUM(Quantity) > AVG(Quantity);
And same issue.
Any help would be appreciated, even an explanation as to why the second one fails.

You might want to take a look at the HAVING clause of SQL.
Note: I'm intentionally not giving you the full answer since this is homework.

why Don't you try this.
SELECT `Cnum` , Sum( Quantity )
FROM `bought`
GROUP BY `Cnum`
HAVING Sum( Quantity ) > ( SELECT AVG( Quantity ) FROM Bought )

Try below:
SELECT Cnum
FROM Bought
having SUM(Quantity) > (SELECT avg(Quantity) FROM Bought)
order by SUM(Quantity) desc

Try this maybe it helps
SELECT Cnum, SUM(Quantity)
FROM Bought
GROUP BY Cnum
HAVING SUM(OrderQuantity) > avg(Quantity)

Try this
SELECT Cnum, Inum, SUM(Quantity) sum, AVG(QUANTITY) average
from bought group by cnum,inum having sum > average

Related

MySQL - Average number of particular product sold on date

I need to write SQL query for "average number of particular product sold by date. On each day is sold min one product".
SELECT AVG (COUNT (PID))
FROM SOLD
GROUP BY DATE, PID;
P.S. PID means Product ID.
Is this query okay?
Should this give right answer?
Consider Using distinct count of date columns
SELECT PID,
COUNT(PID)/COUNT(distinct date_) as "Avg.Product Sold By Days"
FROM SOLD
GROUP BY PID;
You can try this sql query below. Basically, it will return the average number of 'SALES' for each product you have. It will group by each distinct product ID. Please provide us the data structure your of table and etc.
SELECT product_ID, trans_date
Sum(sales_of_product) / COUNT(DISTINCT sold_transaction) AS 'avg'
FROM SOLD
GROUP BY product_ID

MySQL Group Sum amount on the filter by a text

I am working on the sum and if, I am able to get the value (amount_description) of a number for Sum, but I am not sure how I can calculation based on the text (varchar and blue highlight).
As you can see the screenshot as amount, I want the amount based on Amount description on each SKU
So my hope you can advice and how it working
I have tried different many ways but nothing has to work even I write
SELECT SUM(CASE WHEN amount_description = 'commission' and amount_description = 'Commission' and amount_description = 'RefundCommission'THEN amount END) AS sku_TOTAL, transaction_type
FROM settlements
Where transaction_type ='refund'
I am still rookie in mysql.
You can use the SUM function as well as GROUP BY to group all the entries with the same SKU together.
SELECT
`transaction_type`,
`sku`,
SUM(`amount`) AS `sku_total`
FROM
`settlements`
WHERE
`transaction_type` = 'Refund'
AND `amount_description` IN (
'Principal', 'Commission', 'RefundCommission'
)
GROUP BY
`transaction_type`, -- Doesn't really do anything since there is only one type
`sku`
On the comment about not doing anything: MySQL will often allow this query without that, but most DBMS' require that all fields not in aggregate functions must be in the GROUP BY clause. In this case, because there will be only one group (Refund), it doesn't affect the output, and should be included for best practice.
Hello you can use group by and sum to get the sum of each amount_description then filter them using having or where to get only some amount_descriptions
please try
SELECT SUM(amount) AS total, amount_description
FROM settlements
Where transaction_type ='refund'
GROUP BY amount_description
having amount_description="commission" or amount_description="Commission" or
amount_description="RefundCommission"
OR
SELECT SUM(amount) AS total, amount_description,sku
FROM settlements
WHERE transaction_type ='refund'
AND ( amount_description="commission" OR amount_description="Commission" OR
amount_description="RefundCommission" )
GROUP BY amount_description,sku

How to get ONLY the Grand Total of Group Counts?

This code works great for getting both a summary of individual Group counts and a Grand Total combined, but I only want the Grand Total of individual countries with no ROLLUP:
SELECT country, count( * )
FROM mytable
GROUP BY country
WITH ROLLUP
LIMIT 0 , 300
Researching a lot of examples, I was hoping this one would finally work but no joy (can't figure out what the MySQL error is in the code):
SELECT country,COUNT(*)
FROM mytable
GROUP BY country
COMPUTE Sum(Count(*))
Thanks for any assistance!
-stucko
If you want to get the number of rows returned by a GROUP BY you can do something like this
SELECT COUNT(*) FROM (
SELECT country, count( * )
FROM mytable
GROUP BY country
) a /*derived tables need an alias*/

MySQL count records by months on timestampt

I have a MySQL table like this
Transaction(transaction_id, seller_id, sale_date)
where sale_date is a timestamp.
I would like find out the number of sales each seller has made in each month of the last three months. I composed my query like this:
SELECT seller_id, COUNT(*) as num_of_sales
FROM Transaction
WHERE sale_date > '2014-11-30 23:59:59'
GROUP BY seller_id, MONTH(sale_date)
and I am certain that the result is invalid since I got back:
seller_id num_of_sales
2 4829
5 148
and there is no such seller with id 5 in my seller table. Could anyone point me to the right direction, please? Thank you!
Here is a working query that I managed to come up with, hope it is useful for someone:
SELECT
MONTHNAME(sale_date) as d_month,
seller_id,
COUNT(*) as num_of_sales
FROM Transaction
GROUP BY seller_id, d_month
ORDER seller_id, MONTH(sale_date) asc

What is the best way to select rows with maximum value?

I have come across a task, I managed to complete the objective but the solution I got is not optimum, I need more optimum solution. I have used normal Sub Queries May be Correlated Sub Query can solve this better.
This is the table i made
SELECT custid,
count(DISTINCT bid) AS Total
FROM loan
GROUP BY custid;
The output of this is like:-
What I want is the custid having maximum Total.
One way to do it is using Order by Total DESC LIMIT 1 but this will give only 1 result.
What I did is
SELECT custid
FROM (SELECT custid,
count(DISTINCT bid) AS Total
FROM loan
GROUP BY custid) c1
WHERE total = (SELECT max(Total)
FROM (SELECT custid,
count(DISTINCT bid) AS Total
FROM loan
GROUP BY custid) c2)
This gives me correct result that is
What I want to do is reduce the code, because here I am writing the same thing again. I know there must be a simpler way to do it. Maybe a correlated query.
Looking for some good answers. This is basically to clear my concepts only
Sorry, if it is noob question. I am a noob to SQL.
After understand what OP want with #Ravinder 's tip,
I guess build in mysql function GROUP_CONCAT is what you need, sql is:
select custid_count.Total, GROUP_CONCAT(custid_count.custid order by custid_count.custid asc SEPARATOR ',') as custids from
(select custid, count(distinct bid) as Total from loan group by custid order by Total desc) as custid_count
group by custid_count.Total
order by custid_count.Total desc
limit 1;
the result column custids is the max ids concated by ',' ,after the query, you need to split custids by ',' and convert each substring to number type you need,
Here is another way:
select * from loan
where custid =
(
select custid_count.custid from
(select custid, count(distinct bid) as Total from loan group by custid order by Total desc) as custid_count
order by custid_count.Total desc
limit 1
);
First find the custid with max count, then query all rows which match the custid,
I haven't tried this in mysql, but in the sql language I'm using it is fine to use a aggregation function without a group by so something like this
select custid, total, max(total) as maxtotal
from (select custid, count(distinct bid) as total
from loan
group by custid) c1;
would tag on every line both the individual customer total and the table wide max total, and you'd just have to filter on the ones that where the total was equal to the max total. That would give you a final answer of something like this:
select custid
from (select custid, count(distinct bid) as total
from loan
group by custid) c1
where total = max(total);