Skip to content
Advertisement

SQL query to get minimal sum value and associated column from table

I have following tables:

t1 – Items

| Id | Item   |
|  1 | I1     |
|  2 | I2     |

t2 – Item_elements

| Id |  Item_id | Element    | Our_quantity  |  Client_quantity |
|  1 |       1  | E11        |          100  |               0  |
|  2 |       1  | E12        |           20  |             300  |
|  3 |       2  | E21        |          300  |             100  |
|  4 |       2  | E22        |            5  |             300  |

t3 – Element_operations

| Id |  Element_id | Operations_number |
|  1 |           1 |               100 |
|  2 |           1 |                50 |
|  3 |           2 |                50 |
|  4 |           2 |                50 |
|  5 |           3 |                50 |
|  6 |           3 |                50 |
|  7 |           3 |                50 |
|  8 |           3 |                50 |
|  9 |           4 |                10 |
I need SQL query which return table witch items (t1) AND element row associated with item table which has minimum operations number

Desired Output: Table should look like

| Id|Item| Id_el |Our_quantity| Client_quantity | Count Operations_number|
|  1| I1 |     2 |         20 |             300 |                    100 |
|  2| I2 |     4 |          5 |             300 |                     10 |

result

I tried that query

Tried Result:

| Id |  Item_id | Our_quantity  |  Client_quantity |SUM(Operations_number)
|  1 |       1  |          100  |               0  |                   150
|  2 |       1  |           20  |             300  |                   100
|  3 |       2  |          300  |             100  |                   200
|  4 |       2  |            5  |             300  |                    10

What should I do next?

Now I have 2 table:

| Element Id |  Item_id |Sum operations_number for element  |
|  1         |       1  |                          150      |
|  2         |       1  |                          100      |
|  3         |       2  |                          200      |
|  4         |       2  |                           10      |
| Item Id |     Item  |
|  1      |       I1  |
|  2      |       I2  |

How can I join them to get this table?

Item Element who has minimal sum operations number.

| Item Id |     Item  | Element_Id | Sum operations_number for element |
|  1      |       I1  | 2          |                          100      |
|  2      |       I2  | 4          |                           10      |

Advertisement

Answer

You could get desired output using this..

FIDDLE HERE

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