我已经在我的问题得到很好的答案herePostgreSQL的,语法查询问题
所以如果我创建表:
CREATE TABLE IF NOT EXISTS usedfood
(food_code int, name text, qty int, meas text);
INSERT INTO usedfood (food_code, name, qty, meas)
VALUES (10, 'spaghetti', 3, 'pcs'),
(156, 'mayonnaise', 2, 'pcs'),
(173, 'ketchup', 1, 'pcs'),
(172, 'bolognese sauce', 2, 'pcs'),
(173, 'ketchup', 1, 'pcs'),
(10, 'spaghetti', 2, 'pcs'),
(156, 'mayonnaise', 1, 'pcs');
CREATE TABLE IF NOT EXISTS ingredients
(food_code int, ingr_code int, name text, qty decimal(11,3), meas text);
INSERT INTO ingredients (food_code, ingr_code, name, qty, meas)
VALUES (10, 1256, 'spaghetti rinf', 75, 'gramm'),
(156, 1144, 'salt', 0.3, 'gramm'),
(10, 1144, 'salt', 0.5, 'gramm'),
(156, 1140, 'fresh egg', 50, 'gramm'),
(172, 1138, 'tomato', 80, 'gramm'),
(156, 1139, 'mustard', 5, 'gramm'),
(172, 1136, 'clove', 1, 'gramm'),
(156, 1258, 'oil', 120, 'gramm'),
(172, 1135, 'laurel', 0.4, 'gramm'),
(10, 1258, 'oil', 0.4, 'gramm'),
(172, 1130, 'corned beef', 40, 'gramm');
,并从我的PostgreSQL执行这个查询:
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
...我仍然不能得到像这样的预期结果SQL fiddle
我得到这样的错误:
ERROR: syntax error at or near "name" LINE 1: ...code, f.food_code) code, COALESCE(i.name, f.name) name, SUM(...
ERROR: column "f.food_code" must appear in the GROUP BY clause or be used in an aggregate function LINE 1: ...LECT SUM(f.qty) used_times, COALESCE(i.ingr_code, f.food_cod...
ERROR: column "f.name" must appear in the GROUP BY clause or be used in an aggregate function LINE 1: ...(i.ingr_code, f.food_code) code, COALESCE(i.name, f.name) in...
ERROR: column "i.meas" must appear in the GROUP BY clause or be used in an aggregate function LINE 1: ...me, SUM(COALESCE(i.qty, 1) * f.qty) qty, COALESCE(i.meas, f....
ERROR: column "f.meas" must appear in the GROUP BY clause or be used in an aggregate function LINE 1: ...COALESCE(i.qty, 1) * f.qty) qty, COALESCE(i.meas, f.meas) me...
这是最有可能的,这个代码是不是在PostgreSQL完全兼容,所以请,如果有人可以从查询解决这个代码是正确的从PostgreSQL的系统运行。
什么是不清楚关于“*列”f.meas“必须出现在GROUP BY子句*” –
这很清楚,但是当我作为“错误报告”建议我得到不正确的结果。 –
“不正确的结果”太模糊。告诉我们你期望的输出是什么(根据你的样品数据) –