Given I have the following table "PriceRecord":
| PriceRecord_ID | Company_ID | Price | Tarif_type | Tarif_Model | ... attributes |
|:--------------:|:----------:|:-----:|:----------:|:----------:|:--------------:|
| 1 | A | 10 | tarif_1 | Model_1 | ... |
| 2 | A | 20 | tarif_2 | Model_1 | ... |
| 3 | A | 10 | tarif_3 | Model_2 | ... |
| 4 | B | 11 | tarif_1 | Model_2 | ... |
| 5 | B | 15 | tarif_2 | Model_3 | ... |
| 6 | C | 10 | tarif_1 | Model_4 | ... |
My goal is to get the min(Price) for each Company. For each min(Price) I need other attributes (e.g. Tarif_type, Tarif_name) as well.
Expected result:
| PriceRecord_ID | Company_ID | Price | Tarif_type | Tarif_Model | ... attributes |
|:--------------:|:----------:|:-----:|:----------:|:----------:|:--------------:|
| 1 | A | 10 | tarif_1 | Model_1 | ... |
| 4 | B | 11 | tarif_1 | Model_1 | ... |
| 6 | C | 10 | tarif_1 | Model_2 |
I know how to get the min(Price) and group by Company. My Problem is, that I cannot join the other attributes (since the company name is not a unique key.
I tried this query (with the intent to join the table IF both conditions are met --> unfortunately it joins two times for each condtion and I have more than one record for each company in my result table)
subquery = db.session.query(PriceRecord.company_id, db.func.min(PriceRecord.Price).label("minPrice")) \
.group_by(PriceRecord.company_id) \
.subquery()
result = db.session.query(subquery.c.company_id, subquery.c.minPrice, PriceRecord.tarif_type, PriceRecord.tarif_model) \
.join(PriceRecord, subquery.c.insurance_company==PriceRecord.company_id and subquery.c.minPrice==PriceRecord.Price) \
I have found this similar solution but couldn't implement it for my scenario.
Any Help is highly appreciated! thank you in advance