添加到最大/最小函数中相关列的更多信息

问题描述 投票:-1回答:1

我正在使用10.1.39-MariaDB-mariadb.org二进制文件,并且具有下表:

| id  | product   | delivery_date       | issuer   | price_from | price_to | createdAt           | updatedAt           |
|-----|-----------|---------------------|----------|------------|----------|---------------------|---------------------|
| 452 | product 1 | 2019-09-17 22:00:00 | Issuer 1 | 247        | 247      | 2019-09-18 19:03:29 | 2019-09-18 19:03:29 |
| 454 | product 1 | 2019-09-14 22:00:00 | Issuer 2 | 245        | 245      | 2019-09-18 19:03:29 | 2019-09-18 19:03:29 |
| 455 | product 2 | 2019-09-12 22:00:00 | Issuer 3 | 150        | 150      | 2019-09-18 19:03:29 | 2019-09-18 19:03:29 |
| 456 | product 2 | 2019-09-12 22:00:00 | Issuer 4 | 187        | 165      | 2019-09-18 19:03:29 | 2019-09-18 19:03:29 |
| 457 | product 1 | 2019-09-11 22:00:00 | Issuer 5 | 247        | 247      | 2019-09-18 19:03:29 | 2019-09-18 19:03:29 |

我编码了以下查询:

SELECT
    EXTRACT(YEAR
FROM
    rating_date) AS 'Year',
    AVG(`price_from`) AS avg_1y_price_from,
    AVG(`price_to`) AS avg_1y_price_to,
    MAX(`price_from`) AS max_1y_price_from,
    MAX(`price_to`) AS max_1y_price_to,
    MIN(`price_from`) AS min_1y_price_from,
    MIN(`price_to`) AS min_1y_price_to
FROM
    table
GROUP BY
    YEAR(delivery_date)
ORDER BY
    `Year`
DESC

但是,我想为每个汇总函数显示相关的发行者,以便我得到max_1y_price_from具有最大值的发行者。

有关如何添加正确的发行人的任何建议?

感谢您的答复!

mysql sql greatest-n-per-group
1个回答
1
投票

您可以使用join

SELECT y.*, tmaxpfrom.issuer, tmaxpto.issuer, . . . 
FROM (SELECT EXTRACT(YEAR FROM rating_date) AS Year,
             AVG(`price_from`) AS avg_1y_price_from,
             AVG(`price_to`) AS avg_1y_price_to,
             MAX(`price_from`) AS max_1y_price_from,
             MAX(`price_to`) AS max_1y_price_to,
             MIN(`price_from`) AS min_1y_price_from,
             MIN(`price_to`) AS min_1y_price_to
      FROM t
      GROUP BY YEAR(delivery_date)
     ) y LEFT JOIN
     t tmaxpfrom
     ON YEAR(tmaxpfrom.delivery_date) = y.year AND
        tmaxpfrom.price_to = max_1y_price_from LEFT JOIN
     t tmaxpto
     ON YEAR(tmaxpto.delivery_date) = y.year AND
        tmaxpto.price_to = max_1y_price_to LEFT JOIN
     . . . 
ORDER BY `Year` DESC

仅继续查找您想要列表的所有列。

注意:如果有重复项,则该年份将返回多行。

而且,在最新版本的MariaDB中,这会更容易,因此您可以使用窗口函数。

© www.soinside.com 2019 - 2024. All rights reserved.