如何选择多个字段并在一个字段上聚合(或汇总)

时间:2016-08-30 19:58:22

标签: sql postgresql

我需要在几个连接表中创建一个报告,如下所示:

SELECT
  r.recipe_id "Recipe ID"
  ,r.name "Recipe Name"
  ,m.name "Meal Name"
  ,array_agg(distinct(bucket.name)) as "Plans"
  ,mn_sodium.meas_amt "Recipe Sodium"
  ,mn_cholesterol.meas_amt "Recipe Cholesterol"

FROM meals m

-- Join Recipes
INNER JOIN meals_recipe_xref mrx
  ON mrx.meal_id = m.meal_id
INNER JOIN recipes r
  ON r.recipe_id = mrx.recipe_id

-- Determine Plans
LEFT OUTER JOIN plans dmo
  ON dmo.meal_id = mrx.meal_id
LEFT OUTER JOIN calorie_buckets bucket
  ON bucket.bucket_id = dmo.bucket_id

-- Get sodium and cholesterol
LEFT OUTER JOIN recipe_nutrients mn_sodium
  ON mn_sodium.recipe_id = r.recipe_id
  AND mn_sodium.nutri_type_id = 64 -- sodium
LEFT OUTER JOIN recipe_nutrients mn_cholesterol
  ON mn_cholesterol.recipe_id = r.recipe_id
  AND mn_cholesterol.nutri_type_id = 26 -- cholesterol

GROUP BY
  r.name
  ,m.name
  ,r.recipe_id
  ,mn_sodium.meas_amt
  ,mn_cholesterol.meas_amt

ORDER BY m.name

...它给出了给定膳食中每种食谱的钠和胆固醇含量(一顿饭可能含有多种食谱)。

将每餐中的钠和胆固醇值汇总的最佳方法是什么,并在报告中重复这些值?

我试图使用GROUPING SETS,但没有快乐。任何帮助表示赞赏。

enter image description here

1 个答案:

答案 0 :(得分:1)

根据我的理解,您需要@Component class EndpointsEndpoint extends AbstractEndpoint<List<Endpoint>> { private List<Endpoint> endpoints; @Autowired public EndpointsEndpoint(List<Endpoint> endpoints) { super("/"); this.endpoints = endpoints; } @Override public List<Endpoint> invoke() { return endpoints; } } mn_sodium.meas_amtmn_cholesterol.meas_amt的值之和。由于您希望在m.name分区的一组行中得到相同的结果值,因此您可以简单地使用window functionsm.name m.name

PARTITION BY

您可以使用的另一种语法是将窗口命名为重用:

SELECT
  r.recipe_id "Recipe ID"
  ,r.name "Recipe Name"
  ,m.name "Meal Name"
  ,array_agg(distinct(bucket.name)) as "Plans"
  ,mn_sodium.meas_amt "Recipe Sodium"
  ,mn_cholesterol.meas_amt "Recipe Cholesterol"
  ,sum(mn_sodium.meas_amt) OVER(PARTITION BY m.name) AS "Meal Sodium"
  ,sum(mn_cholesterol.meas_amt) OVER(PARTITION BY m.name) "Meal Cholesterol"
FROM
...