我需要在几个连接表中创建一个报告,如下所示:
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
,但没有快乐。任何帮助表示赞赏。
答案 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_amt
每mn_cholesterol.meas_amt
的值之和。由于您希望在m.name
分区的一组行中得到相同的结果值,因此您可以简单地使用window functions,m.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
...