如何获得所需的输出,我试过GROUP BY,但无法获得我想要的

How to obtain the required output, I have tried with GROUP BY, but could not obtain what I want

我有这个table

\d sales_girls

  Column   |         Type         | Collation | Nullable | Default
-----------+----------------------+-----------+----------+---------
 id        | character varying(4) |           |          |
 f_name    | character varying(8) |           |          |
 sale      | integer              |           |          |
 sale_date | date                 |           |          |

SELECT * FROM p8.sales_girls;

  id  | f_name | sale | sale_date
------+--------+------+------------
 E001 | Linda  | 1000 | 2016-01-30
 E002 | Sally  |  750 | 2016-01-30
 E003 | Zindy  |  500 | 2016-01-30
 E001 | Linda  |  150 | 2016-02-01
 E001 | Linda  | 5000 | 2016-02-01
 E002 | Sally  |  250 | 2016-02-01
 E001 | Linda  |  250 | 2016-02-02
 E002 | Sally  |  150 | 2016-02-02
 E003 | Zindy  |   50 | 2016-02-02
(9 rows)

预期产出

我想select每个女孩最大的行

  id  | f_name | sale | sale_date
------+--------+------+------------
 E002 | Sally  |  750 | 2016-01-30
 E003 | Zindy  |  500 | 2016-01-30
 E001 | Linda  | 5000 | 2016-02-01
(9 rows)

我试过了

SELECT id, f_name, MAX(sale), sale_date
FROM p8.sales_girls
GROUP BY f_name; 

你可以这样做:

select id,f_name,sale,sale_date from (        
    select id,f_name,sale,sale_date,max(sale) OVER (PARTITION BY id) max_sale  from  sales_girls 
) a where sale=max_sale

但是如果 Lynda 有两条销量为 5000 的产品线会怎样?

如果在这种情况下你想要最大日期:

select id,f_name,sale,max(sale_date) sale_date from (         
select id,f_name,sale,sale_date,max(sale) OVER (PARTITION BY id) max_sale  from sales_girls 
    ) a where sale=max_sale
group by 1,2,3

使用 PostgreSQL 的 DISTINCT ON 子句:

SELECT DISTINCT ON (id)
       id, f_name, sale, sale_date
FROM p8.sales_girls
ORDER BY id, sale DESC;

您的 table 似乎没有正确规范化,因为 id 似乎识别出 "sales girl"。