PostgreSQL, complex query for calculating ingredients by recipe

后端 未结 1 1222
北荒
北荒 2020-12-22 09:43

I have to calculate food and ingredients of used food stored in PostgreSQL tables:

    table1 \'usedfood\'

food    food                    used    used
code         


        
相关标签:
1条回答
  • 2020-12-22 10:21

    Try

    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
    

    Output:

    | 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 |
    

    Here is SQLFiddle demo

    0 讨论(0)
提交回复
热议问题