PostgreSQL
 sql >> Base de Dados >  >> RDS >> PostgreSQL

PostgreSQL, consulta complexa para calcular ingredientes por receita


Experimentar
SELECT SUM(f.qty) used_times,
       COALESCE(i.ingr_code, f.food_code) code,
       COALESCE(i.name, f.name) name,
       SUM(COALESCE(i.qty, 1) * f.qty) qty,
       COALESCE(i.meas, f.meas) meas
  FROM usedfood f LEFT JOIN ingredients i
    ON f.food_code = i.food_code
 GROUP BY i.ingr_code, i.name

Saída:
| USED_TIMES | CODE |           NAME | QTY |  MEAS |
----------------------------------------------------
|          2 |  173 |        ketchup |   2 |   pcs |
|          2 | 1130 |    corned beef |  80 | gramm |
|          2 | 1135 |         laurel | 0.8 | gramm |
|          2 | 1136 |          clove |   2 | gramm |
|          2 | 1138 |         tomato | 160 | gramm |
|          3 | 1139 |        mustard |  15 | gramm |
|          3 | 1140 |      fresh egg | 150 | gramm |
|          8 | 1144 |           salt | 3.4 | gramm |
|          5 | 1256 | spaghetti rinf | 375 | gramm |
|          8 | 1258 |            oil | 362 | gramm |

Aqui está SQLFiddle demonstração