Order by sum(value) sql - mysql

I am trying to get a list of blog_id and the sum of donations on that blog id from a table called donations. And I want to order it by the sum of donations. Basically I want to produce a list of blogs ranked by donations. Blogs are held in a different table referenced by blog_id.
This is what I have been trying but all it does is sum up all donations and produce 1 row. I don't understand what I did wrong here!
$donations_result = mysql_query("SELECT blog_id, sum(amount) FROM donations ORDER BY sum(amount)");
Donations table is a series of blog_ids and individual donations. So something like this:
blog_id--donation
1 ----------26
1 ----------1
2 ----------24
2 ----------12

You did not group the columns. You need to group it by non-aggregated column and in this case by blog_id
SELECT blog_id, sum(amount) TotalSum
FROM donations
GROUP BY blog_id
ORDER BY TotalSum
The reason why your query executed well without throwing an exception is because mysql permits to use aggregate function without specifying non-aggregated column in the GROUP BY clause.
see MySQL Extensions to GROUP BY

You're missing the GROUP BY operator:
SELECT blog_id, sum(amount)
FROM donations
GROUP BY blog_id
ORDER BY sum(amount)

Related

Need the list of products and orders

This is my homework task:
Products which were ordered along with the 5 most ordered products more than once and the count of orders they were included in. (Do not include the 5 most ordered products in the final result)
Products and orders are in same table. Order detail contain Order detail ID, order id, product id, quantity.
I've tried everything but I'm struggling with "along with" statement in the query.
Here is a query I have tried:
select
productid,
count
(
(select productid from orderdetails)
and
(select productid from orderdetails order by quantity desc limit 5)
) as ORDERS
from orderdetails
group by productid
order by ORDERS desc
You select from orderdetails, aggregate to get one result row per product and you count. It is very common to count rows with COUNT(*), but you can also count expressions, e.g. COUNT(mycolumn) where you just count those that are not null. You are counting an expresssion (because it is not COUNT(*) but COUNT(something else) that you are using). The expression to test for null and count is
(select productid from orderdetails)
and
(select productid from orderdetails order by quantity desc limit 5)
This, however is not an expression that leads to one value that gets counted (when it's not null) or not (when it's null). You are selecting all product IDs from the orderdetails table and you are selecting all the five product IDs from the orderdetails table that got ordered with the highest quantity. And then you apply AND as if these were two booleans, but they are not, they are data sets. Apart from the inappropriate use of AND which is an operator on booleans and not on data sets, you are missing the point here that you should be looking for products in the same order, i.e. compare the order number somehow.
So all in all: This is completely wrong. Sorry to say that. However, the task is not at all easy in my opinion and in order to solve it, you should go slowly, step by step, to build your query.
Products which were ordered along with the 5 most ordered products more than once
Dammit; such a short sentence, but that is deceiving ;-) There is a lot to do for us...
First we must find the 5 products that got ordered most. That means sum up all sales and find the five top ones:
select productid
from orderdetails
group by productid
order by sum(quantity) desc
limit 5
(The problem with this: What if six products got ordered most, e.g. products A, B, and C with a quantity of 200 and products D, E, and F with a quantity of 100? We would get the top three plus two of the top 4 to 6. In standard SQL we would solve this with a ties clause, but MySQL's LIMIT doesn't feature this.)
Anyway. Now we are looking for products that got ordered with these five products along. Does this mean with all five at once? Probably not. We are rather looking for products that were in the same order with at least one of the top five.
with top_5_products as
(query above)
, orders_with_top_5 as
(select orderid
from orderdetails
where productid in (select productid from top_5_products)
)
, other_products_in_order as
(select productid, orderid
from orderdetails
where orderid in (select orderid from orders_with_top_5)
and productid not in (select productid from top_5_products)
And once we've got there, we must even find products that got ordered with some of the top 5 "more than once" which I interpret as to appear in at least two orders containing top 5 products.
with <all the above>
select productid
from other_products_in_order
group by productid
having count(*) > 1;
And while we have counted how many orders the products share with top 5 products, we are still not there, because we are supposed to show the number of orders the products were included in, which I suppose refers to all orders, not only those containing top 5 products. That is another count, that we can get in the select clause for instance. The query then becomes:
with <all the above>
select
productid,
(select count(*) from orderdetails od where od.productid = opio.productid)
from other_products_in_order opio
group by productid
having count(*) > 1;
That's quite a lot for homework seeing that you are struggling with the syntax still. And we haven't even addressed that top-5-or-more ties problem yet (for which analytic functions come in handy).
The WITH clause is available since MySQL 8 and helps getting such a query that builds up step by step readable. Old MySQL versions don't support this. If working with an old version I suggest you upgrade :-) Else you can use subqueries directly instead.

SQL - query with group by and details at the same time

I have sql query like this:
SELECT sum(amount) AS sum, incomes_category_assigned_to_users.name AS category_name
FROM incomes
INNER JOIN incomes_category_assigned_to_users on incomes.income_category_assigned_to_user_id = incomes_category_assigned_to_users.id
WHERE (incomes.user_id = :user_id AND date_of_income >= :first_date AND date_of_income <= :second_date)
GROUP BY incomes.income_category_assigned_to_user_id
ORDER BY sum DESC;
The result is the user incomes grouped by the category - displayed as an array.
I would like to add subquery - get these incomes, not grouped, so that the user can expand the field in array and see it in detail.
Thanks for help
MySQL does not support arrays. One method is to put the values into a string:
SELECT SUM(amount) AS sum,
GROUP_CONCAT(amount) as amounts,
icau.name AS category_name
FROM incomes i JOIN
incomes_category_assigned_to_users icau
ON i.income_category_assigned_to_user_id = icau.id
WHERE i.user_id = :user_id AND
date_of_income >= :first_date AND
date_of_income <= :second_date
GROUP BY icau.name
ORDER BY sum DESC;
Note the changes I made to the query:
The tables have reasonable table aliases. They make the query easier to write and to read.
No parentheses are needed in a WHERE clause that just uses AND.
The GROUP BY keys are now consistent with the unaggregated SELECT columns.

mysql avg function not returning all records

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.

MySQL: using main query variable on sub-sub-query

I'm trying to create query that will show me table of stock, name of the stock, id, date, url, price and list of prices from the last 2 weeks.
For the 14 days history I used sub-query with group_concat on the select.
But when I use group_concat it's return all results and ignore my limit, so I created another sub-query that will be the 14 prices and the group_concat will make it a list.
The table 'record_log' is records for all stocks:
parent_stock_id - the actual stock this line belongs
price - the price
search_date - date of the price
The second table is 'stocks':
id - id of the stock
name, market_volume....
Here is the problem:
In the sub-sub-query (last line of the SELECT), when i'm filtering parent_stock_id=stocks.id he don't recognize the stocks.id because it belongs to the main query.
How can I take the stock_id from top and pass it to the sub-sub-query? or maybe another idea?
SELECT
stocks.id AS stock_id,
record_log.price AS price,
record_log.search_date,
(SELECT GROUP_CONCAT(price) FROM (SELECT price FROM record_log WHERE parent_stock_id=stocks.id ORDER BY id DESC LIMIT 14) AS nevemind) AS history
FROM stocks
INNER JOIN record_log ON stocks.id = record_log.parent_stock_id
WHERE
record_log.another_check !=0
Thank you!
--- I'm are not really using it for stocks, it's just was the easiest way to explain :)
One method is to use substring_index() and eliminate the extra subquery:
SELECT s.id AS stock_id, rl.price AS price, rl.search_date,
(SELECT SUBSTRING_INDEX(GROUP_CONCAT(price ORDER BY id DESC), ',', 14)
FROM record_log rl2
WHERE rl2.parent_stock_id = s.id
) AS history
FROM stocks s INNER JOIN
record_log rl
ON s.id = rl.parent_stock_id
WHERE rl.another_check <> 0;
Note that MySQL has a settable limit on the length of the group_concat() intermediate result (group_concat_max_len). This parameter is defaulted to 1,024.

MYSQL Limit Occurences of a particular column value

Pulling some coupons from a database. Each coupon has a merchantid column that contains the id for the merchant for which the coupon belongs too.
I'm trying to construct a query that pulls 5 coupons, but I only want 1 coupon per merchantid. I don't want multiple coupons with the same merchantid.
You could use
SELECT * FROM coupons GROUP BY merchantid LIMIT 0,5;
And it will work because
MySQL extends the use of GROUP BY so that the select list can refer to nonaggregated columns not named in the GROUP BY clause (see docs)
If you don't want MySQL to decide which merchantid to keep, you can add your condition
(in example below - keep merchant with highest number of clicks) using subquery:
FIXED:
SELECT c1.*
FROM coupons c1 JOIN (
SELECT t.merchantid, MAX(t.numberofclicks) maxnumberofclicks
FROM coupons t GROUP BY t.merchantid
) c2 ON c1.merchantid = c2.merchantid AND c1.numberofclicks = c2.maxnumberofclicks
LIMIT 0,5;
And one more (more concise and probably faster on large datasets) way to skin a cat:
SELECT c1.*
FROM coupons c1 JOIN coupons c2 ON c1.merchantid = c2.merchantid
GROUP BY c1.merchantid, c1.numberofclicks
HAVING c1.numberofclicks = MAX(c2.numberofclicks)
LIMIT 0,5;
If you want 5 coupons with overall highest number of clicks, add ORDER BY c1.numberofclicks DESC before LIMIT 0,5.
try
SELECT * FROM your_table_name GROUP BY merchantid LIMIT 0,5;
this would give 5 rows which has distinct merchantid's, but you may get the same result for different executions. if you want to randomize it, randomize 'A' inside 'LIMIT A,5'.