PostgreSQL:在GROUP BY之后使用LEAST()命令来实现第一个事务

时间:2017-03-27 08:48:26

标签: sql postgresql greatest-n-per-group

我正在使用像这样的magento表:

+-----------+--------------+------------+--------------+----------+-------------+
| date      | email        | product_id | product_type | order_id | qty_ordered |
+-----------+--------------+------------+--------------+----------+-------------+
| 2017/2/15 | x@y.com      | 18W1       | custom       | 12       | 1           |
+-----------+--------------+------------+--------------+----------+-------------+
| 2017/2/15 | x@y.com      | 18W2       | simple       | 17       | 3           |
+-----------+--------------+------------+--------------+----------+-------------+
| 2017/2/20 | z@abc.com    | 22Y34      | simple       | 119      | 1           |
+-----------+--------------+------------+--------------+----------+-------------+
| 2017/2/20 | z@abc.com    | 22Y35      | custom       | 31       | 2           |
+-----------+--------------+------------+--------------+----------+-------------+

我想通过电子邮件分组来创建一个新视图,然后仅使用最少的order_id行。

所以我从上面做这个操作后的最终表应该是这样的:

+-----------+--------------+------------+--------------+----------+-------------+
| date      | email        | product_id | product_type | order_id | qty_ordered |  
+-----------+--------------+------------+--------------+----------+-------------+
| 2017/2/15 | x@y.com      | 18W1       | custom       | 17       | 1           |
+-----------+--------------+------------+--------------+----------+-------------+
| 2017/2/15 | z@abc.com    | 18W2       | simple       |   31     | 3           |
+-----------+--------------+------------+--------------+----------+-------------+

我试图使用以下查询(但它无效):

SELECT * , (SELECT DISTINCT table.email, table.order_id,  
    LEAST (order_id) AS first_transaction_id
FROM
    table
GROUP BY
    email)
FROM table;

真的很喜欢这方面的任何帮助,谢谢!

1 个答案:

答案 0 :(得分:3)

我想你想要distinct on

select distinct on (email) t.*
from t
order by email, order_id;

distinct on是Postgres扩展程序。根据{{​​1}}子句,括号中所有键组合需要一条记录。在这种情况下,每order by行为一行,第一行是email最小的行(因为order_id)。 order by中的键也必须是select中的第一个键。