Help with MySQL query... Need help ordering a group of rows - mysql

I can tell it best by explaining the query I have, and what I need.
I need to be able to get a group of items from the database, grouped by category, manufacturer, and year made. The groupings need to be sorted based on total amount of items within the group. This part is done with the query below.
Secondly, I need to be able to show an image of the most expensive item out of the group, which is why I use MAX(items.current_price). I thought MAX() gets the ENTIRE row corresponding to the largest column value. I was wrong, as MAX only gets the numeric value of the largest price. So the query doesnt work well for that.
SELECT
items.id,
items.year,
items.manufacturer,
COUNT(items.id) AS total,
MAX(items.current_price) AS price,
items.gallery_url,
FROM
ebay AS items
WHERE
items.primary_category_id = 213
AND
items.year <> ''
AND
items.manufacturer <> ''
AND
items.bad_item <> 1
GROUP BY
items.primary_category_id,
items.manufacturer,
items.year
ORDER BY
total DESC,
price ASC
LIMIT
10
if that doesnt explain it well, the results should be something like this
id 10548
year 1989
manufacturer bowman
total 451
price 8500.00 (The price of the most expensive item in the table/ not the price of item 10548)
gallery_url http://ebay.xxxxx (The image of item 10548)
A little help please. Thanks

I've had this same problem, and I'm fairly certain you have to do two queries (or a subquery, that's a matter of taste).
The first query is like what you have (except id isn't helping you).
The second query uses the GROUP BY fields and one (one!) MAX field to get the id and any other meta-data you need.
I believe this is the implementation, although it's hard to test:
SELECT
items.id,
items.year,
items.manufacturer,
items.gallery_url
FROM
ebay as items
NATURAL JOIN
(
SELECT
COUNT(items.id) AS total,
MAX(items.current_price) AS current_price,
items.primary_category_id,
items.manufacturer,
items.year
FROM
ebay AS items
WHERE
items.primary_category_id = 213
AND
items.year <> ''
AND
items.manufacturer <> ''
AND
items.bad_item <> 1
GROUP BY
items.primary_category_id,
items.manufacturer,
items.year
ORDER BY
total DESC,
price ASC
LIMIT
10
) as bigones
ORDER BY
bigones.total DESC,
bigones.current_price ASC
This documentation may help you understand what's going on:
http://dev.mysql.com/doc/refman/5.1/en/group-by-hidden-columns.html
... all rows in each group should have the same values for the columns that are ommitted from the GROUP BY part. The server is free to return any value from the group, so the results are indeterminate unless all values are the same.

Related

Average value for top n records?

i have this SQL Schema: http://sqlfiddle.com/#!9/eb34d
In particular these are the relevant columns for this question:
ut_id,ob_punti
I need to get the average of the TOP n (where n is 4) values of "ob_punti" for each user (ut_id)
This query returns the AVG of all values of ob_punti grouped by ut_id:
SELECT ut_id, SUM(ob_punti), AVG(ob_punti) as coefficiente
FROM vw_obiettivi_2015
GROUP BY ut_id ORDER BY ob_punti DESC
But i can't figure out how to get the AVG for only the TOP 4 values.
Can you please help?
It will give SUM and AVG of top 4. You may replace 4 by n to get top n.
select ut_id,SUM(ob_punti), AVG(ob_punti) from (
select #rank:=if(#prev_cat=ut_id,#rank+1,1) as rank,ut_id,ob_punti,#prev_cat:=ut_id
from Table1,(select #rank:=0, #prev_cat:="")t
order by ut_id, ob_punti desc
) temp
where temp.rank<=4
group by ut_id;
This is not exactly related to the question asked, I am placing this because some one might get benefited.
I got the hackerearth problem to write mysql query to fetch top 10 records based on average of product quantity in stock available.
SELECT productName, avg(quantityInStock) from products
group by quantityInStock
order by quantityInStock desc
limit 10
Note: If someone can make better the above query, please welcome to modify.

Stock system - SQL not showing out of stock items

I have a stock_item table, which houses all stock that has come and gone through my stock system.
Each stock item can be in one of many states, like: 0 ( not_yet_allocated ), 1 ( allocated ), 3 ( returned )... etc.
I am trying to create a notification system that will let me know when I am running low on stock for a specific stock type.
Here is the SQL I have thus far,
SELECT name, status, count(id) AS count
FROM stock_item
WHERE status IN (0,3) /* Items that are not yet allocated (0), or items that have been returned (3) */
GROUP BY name, status
ORDER BY count ASC;
The above SQL works fine, the only problem is that it does not display a stock type if the WHERE clause is not met, in other words, even though there are no items "in stock" for a certain type, I still need that type to be returned with a count of 0.
You need conditional aggregation to see all the items:
SELECT name, status, sum(case when status IN (0,3) then 1 else 0 end) AS count
FROM stock_item
GROUP BY si.name, si.status
ORDER BY count ASC;

Finding The Sum OF Two Values In SQL Server 2008

I have a table Usage and it contains the following columns
sl_No
usage_ID
energyItem_ID
qty
unit_ID
location_ID
p_Rate
Sometimes the same EnergyItem might be located at different locations..
During those conditions how can I get the sum of qty of an individual energyItem..
How to get the sum of the qty of energyItems?
If I've understood correctly, you're trying to find the quantity of each
energy item, regardless of its location, using information in a single table.
The following query will give you the energyItem_ID of each item followed by the total quantity of each item:
SELECT energyItem_ID,Sum(qty) as TotalQuantity
FROM Usage
GROUP BY energyItem_ID
ORDER BY energyItem_ID
If, on the other hand, you wanted the quantity of each energy item, broken down by location, you would need the following:
SELECT location_ID,energyItemID,Sum(qty) as QuantityByLocation
FROM Usage
GROUP BY location_ID,energyItemID
ORDER BY location_ID,energyItemID
The order by clauses make the result easier to follow, but are not strictly necessary.
Finally, the answer by marc_s will give you the quantity of a specific energyItem.
How about:
SELECT EnergyItem_ID, SUM(qty)
FROM dbo.Usage
WHERE EnergyItem_ID = 42 -- or whatever ....
GROUP BY EnergyItem_ID
Or what are you looking for?? The question isn't very clear on the expected output....
select a.usage_ID , b.sum(p_Rate) as total from Table_1 a
inner join Table_2 as b on a.usage_ID = b.usage_ID
group by a.usage_ID

MySQL query for items where average price is less than X?

I'm stumped with how to do the following purely in MySQL, and I've resorted to taking my result set and manipulating it in ruby afterwards, which doesn't seem ideal.
Here's the question. With a dataset of 'items' like:
id state_id price issue_date listed
1 5 450 2011 1
1 5 455 2011 1
1 5 490 2011 1
1 5 510 2012 0
1 5 525 2012 1
...
I'm trying to get something like:
SELECT * FROM items
WHERE ([some conditions], e.g. issue_date >= 2011 and listed=1)
AND state_id = 5
GROUP BY id
HAVING AVG(price) <= 500
ORDER BY price DESC
LIMIT 25
Essentially I want to grab a "group" of items whose average price fall under a certain threshold. I know that my above example "group by" and "having" are not correct since it's just going to give the AVG(price) of that one item, which doesn't really make sense. I'm just trying to illustrate my desired result.
The important thing here is I want all of the individual items in my result set, I don't just want to see one row with the average price, total, etc.
Currently I'm just doing the above query without the HAVING AVG(price) and adding up the individual items one-by-one (in ruby) until I reach the desired average. It would be really great if I could figure out how to do this in SQL. Using subqueries or something clever like joining the table onto itself are certainly acceptable solutions if they work well! Thanks!
UPDATE: In response to Tudor's answer below, here are some clarifications. There is always going to be a target quantity in addition to the target average. And we would always sort the results by price low to high, and by date.
So if we did have 10 items that were all priced at $5 and we wanted to find 5 items with an average < $6, we'd simply return the first 5 items. We wouldn't return the first one only, and we wouldn't return the first 3 grouped with the last 2. That's essentially how my code in ruby is working right now.
I would do almost an inverse of what Jasper provided... Start your query with your criteria to explicitly limit the few items that MAY qualify instead of getting all items and running a sub-select on each entry. Could pose as a larger performance hit... could be wrong, but here's my offering..
select
i2.*
from
( SELECT i.id
FROM items i
WHERE
i.issue_date > 2011
AND i.listed = 1
AND i.state_id = 5
GROUP BY
i.id
HAVING
AVG( i.price) <= 500 ) PreQualify
JOIN items i2
on PreQualify.id = i2.id
AND i2.issue_date > 2011
AND i2.listed = 1
AND i2.state_id = 5
order by
i2.price desc
limit
25
Not sure of the order by, especially if you wanted grouping by item... In addition, I would ensure an index on (state_id, Listed, id, issue_date)
CLARIFICATION per comments
I think I AM correct on it. Don't confuse "HAVING" clause with "WHERE". WHERE says DO or DONT include based on certain conditions. HAVING means after all the where clauses and grouping is done, the result set will "POTENTIALLY" accept the answer. THEN the HAVING is checked, and if IT STILL qualifies, includes in the result set, otherwise throws it out. Try the following from the INNER query alone... Do once WITHOUT the HAVING clause, then again WITH the HAVING clause...
SELECT i.id, avg( i.price )
FROM items i
WHERE i.issue_date > 2011
AND i.listed = 1
AND i.state_id = 5
GROUP BY
i.id
HAVING
AVG( i.price) <= 500
As you get more into writing queries, try the parts individually to see what you are getting vs what you are thinking... You'll find how / why certain things work. In addition, you are now talking in your updated question about getting multiple IDs and prices at apparent low and high range... yet you are also applying a limit. If you had 20 items, and each had 10 qualifying records, your limit of 25 would show all of the first item and 5 into the second... which is NOT what I think you want... you may want 25 of each qualified "id". That would wrap this query into yet another level...
What MySQL does makes perfectly sense. What you want to do does not make sense:
if you have let's say 4 items, each with price of 5 and you put HAVING AVERAGE <= 7 what you say is that the query should return ALL the permutations, like:
{1} - since item with id 1, can be a group by itself
{1,2}
{1,3}
{1,4}
{1,2,3}
{1,2,4}
...
and so on?
Your algorithm of computing the average in ruby is also not valid, if you have items with values 5, 1, 7, 10 - and seek for an average value of less than 7, element with value 10 can be returned just in a group with element of value 1. But, by your algorithm (if I understood correctly), element with value 1 is returned in the first group.
Update
What you want is something like the Knapsack problem and your approach is using some kind of Greedy Algorithm to solve it. I don't think there are straight, easy and correct ways to implement that in SQL.
After a google search, I found this article which tries to solve the knapsack problem with AI written in SQL.
By considering your item price as a weight, having the number of items and the desired average, you could compute the maximum value that can be entered in the 'knapsack' by multiplying desired_cost with number_of_items
I'm not entirely sure from your question, but I think this is a solution to your problem:
SELECT * FROM items
WHERE (some "conditions", e.g. issue_date > 2011 and listed=1)
AND state_id = 5
AND id IN (SELECT id
FROM items
GROUP BY id
HAVING AVG(price) <= 500)
ORDER BY price DESC
LIMIT 25
note: This is off the top of my head and I haven't done complex SQL in a while, so it might be wrong. I think this or something like it should work, though.

How would I do this in MySQL?

Lets say I have a database of widgets. I am showing a list of the top ten groupings of each widget, separated by category.
So lets say I want to show a list of all widgets in category A, but I want to sort them based on the total number of widgets in that category and only show the top 10 groupings.
So, my list might look something like this.
Top groupings in Category A
100 Widgets made by company 1 in 1990.
90 Widgets made by company 1 in 1993.
70 Widgets made by company 3 in 1993.
etc...(for 10 groupings)
This part is easy, but now lets say I want a certain grouping to ALWAYS show up in the listings even if it doesnt actually make the top ten.
Lets say I ALWAYS want to show the number of Widgets made by company 1 in 2009, but I want this grouping to be shown somewhere in my list randomly (not first or last)
So the end list should look something like
Top groupings in Category A
100 Widgets made by company 1 in 1990.
90 Widgets made by company 1 in 1993.
30 Widgets made by company 1 in 2009.
70 Widgets made by company 3 in 1993.
How would i accomplish this in MySQL?
thanks
Edit:
Currently, my query looks like this
SELECT
year,
manufacturer,
MAX(price) AS price,
image_url,
COUNT(id) AS total
FROM
widgets
WHERE
category_id = A
AND
year <> ''
AND
manufacturer <> ''
GROUP BY
category_id,
manufacturer,
year
ORDER BY
total DESC,
price ASC
LIMIT
10
);
Thats without the mandatory grouping in there.
The placement doesnt necessarily have to be random, just shouldnt be on any extreme end. And the list should be 10 groupings including the mandatory listing. So 9 + 1
I would use an UNION query: your current query union the query for 2009, then handle the sorting in the presentation layer.
You can write 2 separate query (one for all companies and another just for company 1) and then use UNION to join them together. Finally, add ORDER BY RAND().
It will look like
SELECT * FROM
(
SELECT company_id, company_name, year, count(*) as num_widgets
....
LIMIT 10
UNION DISTINCT
SELECT company_id, company_name, year, count(*) as num_widgets
...
WHERE company_id =1
...
LIMIT 10
)x
ORDER BY RAND();
You could add a field that you make true for company 1 in 2009 and include it in the where clause. Something like
select * from companies where group = 'some group' or included = true order by included, widgets_made limit 10
For the random part you would have that as subquery then include a column that has a random number from 1 to 10 if the field that you made is true, and rownum otherwise, then sort by that column