I have a table with products, their amount and their price. I need to select all entries where the average price per article is between a range.
My query so far:
SELECT productid,AVG(SUM(price)/SUM(amount)) AS avg
FROM stock WHERE avg>=$from AND avg<=$to GROUP BY productid
If do this, it tells me avg doesn't exist.
Also I obviously need to group by because the sum and average need to be per wine
You need to put it in the HAVING clause. You cannot filter by the result of aggregates using WHERE.
MySQL does allow you to reference column aliases in HAVING. You might need
SELECT
productid,
AVG(price/amount) AS avg ,
/*SUM(price)/SUM(amount) AS avg (<--- Or perhaps this?)*/
FROM stock
GROUP BY productid
HAVING avg>=$from AND avg<=$to
But I'm not sure exactly what you are trying to do with AVG(SUM(price)/SUM(amount)) can you show some example data?
Related
Why do I not get the same results when running the two queries? If I run the second one I get the course with the smallest amount of credits and when I run the first one I get the courses ordered by courseid
select min(credits), title, courseid
from course
group by title, courseid
select min(credits)
from course
An aggregation query is any query that has a group by or an aggregation function in the select.
An aggregation query returns one row per group, where a "group" is defined as the unique combination of values of the keys in the group by clause. If there is no group by clause, then all rows are taken to be a single group and one row is returned.
So, your first query returns one row for each combination of title and courseid in the course table. That row contains the minimum value of credits for that combination. If the course table has only one row per courseid, then the results are very similar to the contents of the table.
The second query returns one row overall, with the minimum number of credits of all rows.
If you want to get one row from with the minimum number of credits, then you don't want an aggregation query. Instead, you can use:
select c.*
from course c
order by c.credits
limit 1;
When you use a group by, you are using a sort of "filter", in the first query you group by title, then all the same titles are grouped by courseid, in the second you only select the minimum value of credits without filtering.
Take a look at a group by doc maybe with some graphical examples like this:
https://www.geeksforgeeks.org/sql-group-by/
i've managed to write an SQL Query on prestashop to export products and combinations with attributes from my ecommerce. Now i would like to filter results, to get only the cheapest combination for every product.
For example, i got this table with 2 products and 3 possible combination for each:
product-price
A 22€
A 44€
A 100€
B 15€
B 30€
B 45€
I would like to know if there's a way with SQL query, using WHERE command or any other, to filter combinations within a product, giving only the cheapest one as result.
So the result of the query SQL would be:
product -price
A 22€
B 15€
Is it possible please?
Have you tried a simple aggregation query?
select product, min(price) as cheapest_price
from mytable
group by product;
This will give you the lowest value of price for each value of product.
A simple GROUP BY query should work:
SELECT product, MIN(price) AS min_price
FROM yourTable
GROUP BY product;
Edit:
If your price data is in fact text, with a Euro symbol occurring at the end of each price string, then you'll have to remove it, and cast to integer before taking the min:
SELECT
product,
MIN(CAST(LEFT(price, CHAR_LENGTH(price) - 1) AS UNSIGNED)) AS min_price
FROM yourTable
GROUP BY product;
Demo
But, it would be best to not store currency symbols and numeric price data together in the same column. Instead, you could add a number column which would maintain to what currency a price corresponds. Then, you would only need to use my first query to get the answer you want.
I am using the following query:
SELECT mgap_growth
FROM mgap_orders
WHERE account_manager_id = '159795'
GROUP BY mgap_ska_report_category
mgap_growth is a column with identical amounts that differ only per mgap_ska_report_category, which is the reason for the grouping. Now hat I have normalized the individual amounts per category, how can I use SUM to tally their total?
Here is a screenshot of the data:
I only need the SUM of the growth amounts per category, not of all of the mgap_growth records, but Im unsure as to how to SUM after the grouping.
Thanks!
EDIT FOR ADDITIONAL QUERY:
Let me throw another issue into the mix: we know I need to SUM only once per category, but what if I needed to GROUP BY CUSTOMER? I just found out that there are multiple customers in the data, each is duplicated per growth record, but differ by category. I really need to use two groupings, one for category to single out and SUM the growth amount and then another the single out the customer.
Here is an image describing the data:
If I understand you correctly, you need to sum the results from the subquery.
SELECT SUM(mgap_growth) AS total_mgap_growth
FROM (SELECT mgap_growth
from mgap_orders
WHERE account_manager_id = '159795'
GROUP BY mgap_ska_report_category) AS x
This should should show the total growth per category for that particular account manager:
SELECT sum(mgap_growth) AS Growth, mgap_ska_report_category as Category
FROM mgap_orders
WHERE account_manager_id = '159795'
GROUP BY mgap_ska_report_category
Rather than thinking of doing the SUM after the grouping, you can do the two together in the one statement. You were 99% of the way there with what you had already.
To answer your additional question in the comment, you can add another column to group by. The order that you list them in the group by section is the important part. The overall grouping comes first. So assuming 'Customer' is the customer column name you would do this:
SELECT mgap_ska_report_category as Category, Customer, sum(mgap_growth) AS Growth
FROM mgap_orders
WHERE account_manager_id = '159795'
GROUP BY mgap_ska_report_category, customer
WITH ROLLUP
Note that changing the SELECT columns in the top line was just for aesthetics, you can put them in any order and will get the same data, but this will be the easiest to read.
This shows the growth per customer by category for that particular account manager.
Edited again to add WITH ROLLUP. This will give you the totals per category as well. Try it with and without the WITH ROLLUP to see the how it changes things.
I am trying to get this simple query to work. I like to know how many times a certain vouchercode has been used and what the total discount value is per used voucher code.
The database table has fields discount_value, discount_data. The discount_data holds the vouchercode and discount_value the sum of discount per purchase id.
SELECT discount_data,
COUNT(*)
FROM wp_wpsc_purchase_logs
GROUP BY
discount_data
seems to work to get amount of voucher code used.
But how do i get the total discount_value per used voucher code?
regards
Is the SUM() function what you are looking for?
SELECT discount_data, COUNT(*), SUM(discount_value)
FROM wp_wpsc_purchase_logs
GROUP BY discount_data
Sum() function may be
SELECT discount_data, SUM(discount_value), count(*)
FROM wp_wpsc_purchase_logs
GROUP BY discount_data
I have table orders with fields id, customer_id and amt:
SQL Fiddle
And I want get customer_id with the largest amt and value of this amt.
I made the query:
SELECT customer_id, MAX(amt) FROM orders;
But the result of this query contained an incorrect value of customer_id.
Then I built such the query:
SELECT customer_id, MAX(amt) AS maximum FROM orders GROUP BY customer_id ORDER BY maximum DESC LIMIT 1;
and got the correct result.
But I do not understand why my first query not worked properly. What am I doing wrong?
And is it possible to change my second query to obtain the necessary information to me in a simpler and competent way?
MySQL will allow you to leave GROUP BY off of a query, thus returning the MAX(amt) in the entire table with an arbitrary customer_id. Most other RDBMS require the GROUP BY clause when using an aggregate.
I don't see anything wrong with your 2nd query -- there are other ways to do it, but yours will work fine.
Some versions of SQL give you a warning or error when you select a field, have an aggregate operator like MAX or SUM, and the field you are selecting does not appear in GROUP BY.
You need a more complicated query to fetch the customer_id corresponding to the max amt. Unfortunately SQL is not as naive as you think. Once such way to do this is:
select customer_id from orders where amt = ( select max(amt) from orders);
Although a solution using joins is likely more performant.
To understand why what you were trying to do doesn't make sense, replace MAX with SUM. From the stance of how aggregate operators are interpreted, it's a mere coincidence that MAX returns something that corresponds to an actual row. SUM does not have this property, for instance.
Practically your first query can be seen as if it were GROUP BY-ed into a big single group.
Also, MySQL is free to choose each output value from different source rows from the same group.
http://dev.mysql.com/doc/refman/5.7/en/group-by-extensions.html
MySQL extends the use of GROUP BY so that the select list can refer to
nonaggregated columns not named in the GROUP BY clause.
The server is free to choose any value from each group, so
unless they are the same, the values chosen are indeterminate.
Furthermore, the selection of values from each group cannot be
influenced by adding an ORDER BY clause. Sorting of the result set
occurs after values have been chosen, and ORDER BY does not affect
which values within each group the server chooses.
The problem with MAX() is that it will select the highest value of that specified field, considering the specified field alone. The other values in the same row are not considered or given preference for the result at any degree. MySQL will usually return whatever value is the first row of the GROUP (in this case the GROUP is composed by the entire table sinse no group was specified), dropping the information of the other rows during the agregation.
To solve this, you could do that:
SELECT customer_id, amt FROM orders ORDER BY amt DESC LIMIT 1
It should return you the customer_id and the highest amt while preserving the relation between both, because no agregation was made.