SQL SELECT MIN value with WHERE statement - mysql

I'm trying to get the lowest price of a specific quote on SQL. I tried the following with erroneous results:
SELECT * FROM price WHERE price=(SELECT MIN(price) as price FROM price WHERE id_quote=36
SELECT id_provider, MIN(price) as price FROM price WHERE id_quote=36
I understand that I'm getting multiple results on the first query if I have the same price in that table regardless of the quote. But I don't know why the second isn't giving me the correct results.
I need to call only id_provider and its price from that specific quote (no group).
Any help?

I think you just need a correlated subquery:
SELECT p.*
FROM price p
WHERE p.id_quote = 36 AND
p.price = (SELECT MIN(p2.price) FROM price p2 WHERE p2.id_quote = p.id_quote);
Notice that the "quote" condition has moved to the outer query.

I like using RANK() for this kind of problem:
SELECT id_quote, id_provider, price
FROM
(
SELECT id_quote id_provider, price,
RANK() OVER(PARTITION BY id_quote ORDER BY price ASC) AS rnk
FROM price
) sub
WHERE rnk = 1

You can do it this way if you want:
SELECT TOP 1 id_provider, price FROM price WHERE id_quote=36 ORDER BY price ASC

Related

How to sum when they have same color with sql?

I have this table
i want to ignore productNo and sum all product count accordingly.
select sum(count), max(productNo)
from Table
where date between 117 and 118
group by product
this one gives wrong result...
I want to have sum of counts for each Product-ProductNo combination
try like below
select product,productno,sum(count) as result
from table_name
where productno='X1'
group by product,productno
seems you need the firts rows order by result
select product,productno,sum(count) as result
from table
group by product,productno
order by result
limit 1
Since you haven't tagged any DBMS so, i would use row_number():
select t.*
from (select product, productno, sum(count) as cnt,
row_number() over (partition by product order by sum(count) desc) as seq
from table t
group by product, productno
) t
where seq = 1;
You can also use LIMIT clause (but not for each product) :
select product, productno, sum(count) as cnt
from table t
group by product, productno
order by cnt desc
limit 1;
Some other DBMS requires TOP clause instead of LIMIT clause so, you can change accordingly but the idea would be same.
select sum(count), max(productNo)
from Table
where date between 117 and 118
group by product, productNo
with this it works :)

SELECT the customer who has ordered the greatest quantity of Products in the case of two customers

I have the following ORDERS table
I know query to select the customer that has ordered the greatest quantity. However, how would it work, if say, two customers have the same quantity. What query should I write to show both the customers?
You can use a subquery which checks that the quantity for a given record matches the largest quantity observed in the table:
SELECT *
FROM yourTable
WHERE qty = (SELECT MAX(qty) FROM yourTable)
This will return multiple records if there are more than one customer sharing the maximum quantity.
If you only wanted to get back a single record, even in the presence of ties, you could use this approach:
SELECT *
FROM yourTable
ORDER BY qty DESC
LIMIT 1
I think you want sum of qty per custNum.
If so you can try like:
select custNum,
sum(qty) as qty
from Orders
group by custNum
order by sum(qty) desc;
Fiddle here:
http://sqlfiddle.com/#!9/47931b/10
SELECT custnum,sum(qty) as total
FROM orders
group by custnum
having sum(qty) = (SELECT MAX(qty) FROM orders);
This will return both values.

MySQL select group by having column != x

I'm trying to select rows where a certain column does not have a certain value, such as 0, but I'm unable to get this to work.
SELECT *
FROM rentals
GROUP BY date, rooms, price
HAVING show_independently < 1
If show_independently is 1, then I don't want to group them. However, this statement shows no rows even though most rows have show_independently as 0.
SELECT date, rooms, price
FROM rentals
WHERE show_independently < 1
GROUP BY date, rooms, price
If you only want to group some rows and leave others ungrouped, you can use a UNION:
SELECT *
FROM rentals
WHERE show_independently <> 1
GROUP BY date, rooms, price
UNION ALL
SELECT *
FROM rentals
WHERE show_independently = 1
This groups only those where show_independently is not 1, and includes the rest without grouping them.
A HAVING clause is used when you are using an aggregate function to filter data.
A typical query with HAVING:
SELECT yourColumn, aggregate_function(otherColumn)
FROM yourTable
WHERE yourColumn = someValue
GROUP BY yourColumn
HAVING aggregate_function(otherColumn) = someOtherValue
I think you want to be using a WHERE clause:
SELECT date, rooms, price
FROM rentals
WHERE show_independently < 1
GROUP BY date, rooms, price

How to select data where a field has a min value in MySQL?

I want to select data from a table in MySQL where a specific field has the minimum value, I've tried this:
SELECT * FROM pieces WHERE MIN(price)
Please any help?
this will give you result that has the minimum price on all records.
SELECT *
FROM pieces
WHERE price = ( SELECT MIN(price) FROM pieces )
SQLFiddle Demo
This is how I would do it, assuming I understand the question.
SELECT * FROM pieces ORDER BY price ASC LIMIT 1
If you are trying to select multiple rows where each of them may have the same minimum price, then #JohnWoo's answer should suffice.
Basically here we are just ordering the results by the price in ascending order (ASC) and taking the first row of the result.
This also works:
SELECT
pieces.*
FROM
pieces inner join (select min(price) as minprice from pieces) mn
on pieces.price = mn.minprice
(since this version doesn't have a where condition with a subquery, it could be used if you need to UPDATE the table, but if you just need to SELECT i would reccommend to use John Woo solution)
Use HAVING MIN(...)
Something like:
SELECT MIN(price) AS price, pricegroup
FROM articles_prices
WHERE articleID=10
GROUP BY pricegroup
HAVING MIN(price) > 0;
Efficient way (with any number of records):
SELECT id, name, MIN(price) FROM (select * from table order by price) as t group by id
In fact, depends what you want to get:
- Just the min value:
SELECT MIN(price) FROM pieces
A table (multiples rows) whith the min value: Is as John Woo said above.
But, if can be different rows with same min value, the best is ORDER them from another column, because after or later you will need to do it (starting from John Woo answere):
SELECT * FROM pieces
WHERE price = ( SELECT MIN(price) FROM pieces)
ORDER BY stock ASC
To improve #sberry's answer, if the column has a null value then simply doing ORDER BY would select a row with null value. Add a WHERE clause to get correct results:
SELECT * FROM pieces
WHERE price>0
ORDER BY price ASC
LIMIT 1;
Or if there is a chance of having negative values and/or VARCHAR, etc. do:
SELECT * FROM pieces
WHERE price IS NOT NULL
ORDER BY price ASC
LIMIT 1;
To make it simpler
SELECT *,MIN(price) FROM prod LIMIT 1
Put * so it will display the all record of the minimum value

Finding the 2nd most expensive total products in MySQL

I'm working on simple queries to learn MySQL, in my example database, I keep track of Stores which sells electronic devices, I have a table Sells(Store, Item, Price).
And example data is,
'Best Buy', 'Galaxy S', 1000
'Buy More', 'Macbook Air', 2000
'Best Buy', 'Microsoft Mouse', 20
'Best Buy', 'Macbook Pro Cover', 40
'Buy More', 'Asus Zenbook', 2000
And so on..
I tried the following sql statement, but it says:
Error Code: 1111. Invalid use of group function 0.000 sec
SELECT store
FROM sells
WHERE SUM(price) <
(SELECT SUM(price) AS total
FROM sells
GROUP BY store
ORDER BY total DESC
LIMIT 1)
GROUP BY store
ORDER BY SUM(price) DESC
I would be appreciate if you can help me
Thanks
This will just plain show the second most expensive store;
SELECT STORE
FROM TABLE_A
GROUP BY STORE
ORDER BY SUM(PRICE) DESC
LIMIT 1,1
Demo here.
If you want the price displayed too, you can just select that too;
SELECT STORE, SUM(PRICE) TOTAL_PRICE
FROM TABLE_A
GROUP BY STORE
ORDER BY TOTAL_PRICE DESC
LIMIT 1,1
Demo here.
Edit: If you have several most expensive stores and several second most expensive stores, the query to get the all the second most expensive ones becomes quite a bit more convoluted; I'm sure someone can beat the efficiency of this one;
SELECT STORE, SUM(PRICE) TOTAL_PRICE
FROM TABLE_A
GROUP BY STORE
HAVING TOTAL_PRICE =
(SELECT SUM(PRICE) TMP
FROM TABLE_A
GROUP BY STORE
HAVING TMP <
(SELECT SUM(PRICE) TMP2
FROM TABLE_A
GROUP BY STORE
ORDER BY TMP2 DESC
LIMIT 1)
ORDER BY TMP DESC LIMIT 1)
Demo here.
You can do like this;
SELECT *,
SUM(price) AS totalprice
FROM sells
GROUP BY store
ORDER BY totalprice DESC
LIMIT 2
You first select the sum of the prices and store it temporarily in for ex. totalprice then as you already did group by store. To get the most expensive stores order the sum backwards and then limit to just two results.
You will be able to get the totalprice just as an ordinary column when you loop out the results
almost correct,
SELECT SUM(price) as price_total FROM sells GROUP BY store
if you want to order by you can do subquery, like:
SELECT price_total FROM (SELECT SUM(price) as price_total FROM sells GROUP BY store) as res ORDER BY price LIMIT 2
if you want to take 2nd you might make another query but i think it is better to use your back-end language
SELECT distinct price from sells ORDER BY price DESC, and in your code, just take the second one.
If you need the rest of the info, do this:
SELECT * from sells
WHERE price = (SELECT distinct price from sells ORDER BY price DESC LIMIT 1,1)
didn'T test it but should work
SELECT S.store
FROM (
SELECT SUM(T.price) AS sum_price
FROM formList_Total AS T
GROUP BY T.store
) AS S
ORDER BY sum_price DESC
LIMIT 1 , 1
Sorry, went to testing, here what i ended up with.