所有行中重复列的最小值和最大值

时间:2016-02-22 05:52:10

标签: mysql sql max normalization min

我有一个orders表,其中包含supplier_id列和revenue列:

enter image description here

每个供应商的总收入表如下:

SELECT
  supplier_id,
  SUM(revenue) as total_revenue
FROM
  orders
GROUP BY
  supplier_id

我想将收入标准化为0到1:

enter image description here

因此,我需要所有供应商的所有总收入的minmax

如果可能,请将这些值作为每行重复的其他列:

enter image description here

我如何在MySQL中执行此操作?

请注意,我希望所有供应商的总收入 minmax ,而不是每个供应商的订单中的最小和最大收入。

2 个答案:

答案 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