Skip to content
Advertisement

How to return the maximum and minimum values for specific ID SQL

Given the following SQL tables: https://imgur.com/a/NI8VrC7. For each specific ID_t I need to return the MAX() and MIN() value of Cena_c(total price) column of a given ID_t.

| ID_t | Nazwa |
| ---- | ----- |
| 1    | T1    |
| 2    | T2    |
| 3    | T3    |
| 4    | T4    |
| 5    | T5    |
| 6    | T6    |
| 7    | T7    |
| ID   | ID_t | Ilosc | Cena_j | Cena_c | ID_p |
| ---- | ---- | ----- | ------ | ------ | ---- |
| 100  | 1    | 1     | 10     | 10     | 1    |
| 101  | 2    | 3     | 20     | 60     | 2    |
| 102  | 4    | 5     | 10     | 50     | 7    |
| 103  | 2    | 2     | 20     | 40     | 5    |
| 104  | 5    | 1     | 30     | 30     | 5    |
| 105  | 7    | 6     | 80     | 480    | 1    |
| 106  | 6    | 7     | 15     | 105    | 2    |
| 107  | 6    | 5     | 15     | 75     | 1    |
| 108  | 3    | 3     | 25     | 75     | 7    |
| 109  | 7    | 1     | 80     | 80     | 5    |
| 110  | 4    | 1     | 10     | 10     | 2    |
| 111  | 2    | 9     | 20     | 180    | 2    |

Based on provided tables the correct result should look like this:

| ID_t  | Cena_c_max | Cena_c_min |
| ----- | ---------- | ---------- |
| T1    | 10         | 10         |
| T2    | 180        | 60         |
| T3    | 75         | 75         |
| T4    | 50         | 10         |
| T5    | 30         | 30         |
| T6    | 105        | 75         |
| T7    | 480        | 80         |

Is this even possible? I haven’t found anything yet that I could use to implement my solution.

Advertisement

Answer

SELECT concat('T',ID_t), max(Cena_c) as Cena_c_max, min(Cena_c) as Cena_c_min FROM table GROUP BY ID_t

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement