我有一个orders
表,其中包含supplier_id
列和revenue
列:
每个供应商的总收入表如下:
SELECT
supplier_id,
SUM(revenue) as total_revenue
FROM
orders
GROUP BY
supplier_id
我想将收入标准化为0到1:
因此,我需要所有供应商的所有总收入的min
和max
。
如果可能,请将这些值作为每行重复的其他列:
我如何在MySQL中执行此操作?
请注意,我希望所有供应商的总收入 min
和max
,而不是每个供应商的订单中的最小和最大收入。
答案 0 :(得分:2)
您可以尝试使用JOIN
SELECT
t1.supplier_id,
t1.total_revenue,
t2.max_total_revenue,
t2.min_total_revenue
FROM (
SELECT
supplier_id,
SUM(revenue) as total_revenue
FROM orders
GROUP BY supplier_id
) t1
LEFT JOIN (
SELECT
MAX(total_revenue) max_total_revenue,
MIN(total_revenue) min_total_revenue
FROM (
SELECT
supplier_id,
SUM(revenue) as total_revenue
FROM orders
GROUP BY supplier_id
)
) t2 ON 1 = 1
答案 1 :(得分:0)
这是使用变量来确定最小值和最大值
的方法SELECT supplier_id,
total_revenue,
@min,
@max
FROM (
SELECT supplier_id,
total_revenue,
@min := coalesce(@min,total_revenue),
@max := total_revenue
FROM (
SELECT
supplier_id,
SUM(revenue) as total_revenue
FROM orders
GROUP BY supplier_id
ORDER BY total_revenue
) t
) t