I am getting started with SQLite
. I have done a pair of tutorials that have given me a global view of SQL
statements. I think I would be able to fulfill my task with several simple queries. However, and for academic reasons, I would like to combine them into a somewhat more complex query.
Let's take a look at my problem, let's say I have this table PRODUCTS:
+---------+-------+--------+-------------+
| Product | Kcal | Price | Supermarket |
+---------+-------+--------+-------------+
milk 300 1.01 Carrefour
eggs 75 1.50 Carrefour
bread 400 1.99 Carrefour
milk 150 1.20 Lidl
eggs 50 2.00 Lidl
bread 300 1.50 Lidl
And let's say I want this output:
+-------------+----------+---------+-----------+---------+
| Supermarket | Max Kcal | Product | Min Price | Product |
+-------------+----------+---------+-----------+---------+
Carrefour 400 bread 1.01 milk
Lidl 300 bread 1.20 milk
My simple query to retrive the keys associated to a max/min value is:
sql = ('SELECT PRODUCT, Supermarket '
'from PRODUCTS '
'where KCAL = (SELECT MAX(KCAL) from PRODUCTS) ')
I have tried to use GROUP BY
statement in order to retrieve all max "kcal" grouped by "supermarket".
sql = ('SELECT Supermarket, MAX(KCAL), Product '
'from PRODUCTS '
'group by Supermarket '
'order by Supermarket ')
As well as all min "prices" grouped by "supermarket".
sql = ('SELECT Supermarket, MIN(Price), Product '
'from PRODUCTS '
'group by Supermarket '
'order by Supermarket ')
I do not find any clues on how to combine, however, these two queries in a single one with the goal of acessing the database one single time and reduce the expended time.
Is it even possible? or am I forced to do several queries?
I might have over-simplified my problem, but I have a 500MB database with plenty of tables for which I need each time a max/min value sorted by a common key ("supermarket"). I would need a lot of queries that take several minutes each time...
I wonder if it does make a difference if Kcals and Prices are in different tables, I have not yet tried to combine queries from different tables (I go from simple to complex).
Thank YOU!