gpt4 book ai didi

mysql - 无效操作: column "[column_name]" must appear in the GROUP BY clause or be used in an aggregate function;

转载 作者:行者123 更新时间:2023-11-29 09:30:43 24 4
gpt4 key购买 nike

我已经阅读了近 10 多个与我的问题相关的问题,但没有人能解决我的问题。因为我的数据库中有 3 个表,我正在尝试计算它们相对于时间的销售额(年销售额)。我需要按date_added对我的查询进行GROUP BY。在 MYSQL 中它工作得很好并且给了我很好的结果,但是在 redshift 中我被卡住了。

MYSQL 查询:

SELECT
MONTHNAME(o.date_added) AS MONTH,
YEAR(o.date_added) AS YEAR,
COUNT(o.order_id) AS orders,
FROM
order o
LEFT JOIN(
SELECT
op.order_id,
SUM(op.quantity) AS op_qty,
SUM(op.total) AS total,
SUM(op.cost) AS cost
FROM
order_product op
GROUP BY
op.order_id
) op
ON
op.order_id = o.order_id
LEFT JOIN(
SELECT
order_id,
SUM(IF(CODE = 'coupon', VALUE, 0)) AS coupon
FROM
order_total
WHERE
1
GROUP BY
order_id
) ot
ON
ot.order_id = o.order_id
WHERE
(
DATE(o.date_added) >= DATE_ADD(NOW(), INTERVAL - 24 MONTH) AND DATE(o.date_added) <=
DATE(NOW())) AND(o.order_status_id = '22' OR o.order_status_id = '23')
GROUP BY
MONTH(o.date_added),
YEAR(o.date_added)
ORDER BY
date_added ASC
LIMIT 0, 25

这个 MYSQL 查询工作得很好,但是当我将其转换为 RedShift 的 POSTGRE 格式时,它给了我错误 无效操作:列“o.date_added”必须出现在 GROUP BY 子句中或在聚合函数中使用;

POSTGRES 查询:

SELECT
EXTRACT(MONTH FROM o.date_added) AS month,
EXTRACT(YEAR FROM o.date_added) AS year,
COUNT(o.order_id) AS orders
FROM
orders o
LEFT JOIN
(
SELECT
op.order_id,
SUM(op.quantity) AS op_qty,
SUM(op.total) AS total,
SUM(op.cost) AS cost
FROM
order_product op
GROUP BY
op.order_id
) op
ON op.order_id = o.order_id
LEFT JOIN
(
SELECT
order_id,
SUM(CASE
WHEN CODE = 'coupon' THEN VALUE
ELSE 0
END) AS coupon
FROM
order_total
WHERE
1
GROUP BY
order_id
) ot
ON ot.order_id = o.order_id
WHERE
(
DATE(o.date_added) >= now() + interval '-24 month'
AND DATE(o.date_added) <= DATE(NOW())
)
AND (
o.order_status_id = '22'
OR o.order_status_id = '23'
)
GROUP BY
(EXTRACT(MONTH FROM o.date_added), EXTRACT(YEAR FROM o.date_added))
ORDER BY
o.date_added ASC LIMIT 25

postgre查询中是否有任何语法错误以及为什么我需要在GROUP BY中添加o.date_add

最佳答案

您的ORDER BY子句中有o.date_added,但您的实际结果集没有它。 ORDER BY 在查询完成后完成。

您可以使用:

ORDER BY month asc, year asc LIMIT 25

此外,您还可以从 GROUP BY 中删除多余的括号:

GROUP BY EXTRACT(MONTH FROM o.date_added), EXTRACT(YEAR FROM o.date_added)

DB-Fiddle

请参阅 Redshift documentation用于使用 now() 函数。使用 getdate() 代替,因为 now() 似乎是 deprecated .

关于mysql - 无效操作: column "[column_name]" must appear in the GROUP BY clause or be used in an aggregate function;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58800348/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com