gpt4 book ai didi

SQL:更新 GROUP BY 以包含基于另一列最大值的值

转载 作者:行者123 更新时间:2023-11-29 12:51:49 25 4
gpt4 key购买 nike

问题

在查询中使用 GROUP BY 语句和聚合函数时,如何从列中添加特定值?

概览

这是我的表格示例:

id  | year | quarter | wage | comp_id | comp_industry |
123 | 2012 | 1 | 1000 | 456 | abc |
123 | 2012 | 1 | 2000 | 789 | def |
123 | 2012 | 2 | 1500 | 789 | def |
456 | 2012 | 1 | 2000 | 321 | ghi |
456 | 2012 | 2 | 2000 | 321 | ghi |

为了按quarterwage 计算每个人的wage 值之和,我运行了以下查询:

SELECT SUM(wage) AS sum_wage
FROM t1
GROUP BY id, year, quarter, sum_wage;

结果在

id  | year | quarter | sum_wage | 
123 | 2012 | 1 | 3000 |
123 | 2012 | 2 | 1500 |
456 | 2012 | 1 | 2000 |
456 | 2012 | 2 | 2000 |

期望的输出

我想更新我的查询以包括 comp_industry 列,其中个人的 wage 在每个 quarteryear 中最高。我不确定从哪里开始,所以我只返回每个季度年度人们赚取最多收入的行业。

id  | year | quarter | sum_wage | comp_industry
123 | 2012 | 1 | 3000 | def
123 | 2012 | 2 | 1500 | def
456 | 2012 | 1 | 2000 | ghi
456 | 2012 | 2 | 2000 | ghi

我查看了 Get value based on max of a different column grouped by another columnFetch the row which has the Max value for a column,但不确定从那里去哪里。

如有任何帮助或建议,我们将不胜感激!

最佳答案

您可以尝试将窗口函数SUMROW_NUMBER 一起使用。

idyearquarter 列按wage desc 排序然后得到 rn = 1.

架构(PostgreSQL v9.6)

CREATE TABLE T (
id INT,
year INT,
quarter INT,
wage INT,
comp_id INT,
comp_industry VARCHAR(50)
);


INSERT INTO T VALUES (123 , 2012 , 1 , 1000 , 456 ,'abc');
INSERT INTO T VALUES (123 , 2012 , 1 , 2000 , 789 ,'def');
INSERT INTO T VALUES (123 , 2012 , 2 , 1500 , 789 ,'def');
INSERT INTO T VALUES (456 , 2012 , 1 , 2000 , 321 ,'ghi');
INSERT INTO T VALUES (456 , 2012 , 2 , 2000 , 321 ,'ghi');

查询#1

SELECT id, year,quarter ,sum_wage, comp_industry FROM (
SELECT *,
SUM(wage) OVER (PARTITION BY id, year, quarter order by year ) sum_wage,
ROW_NUMBER() OVER (PARTITION BY id, year, quarter order by wage desc) rn
FROM T
) t1
where rn = 1;

| id | year | quarter | sum_wage | comp_industry |
| --- | ---- | ------- | -------- | ------------- |
| 123 | 2012 | 1 | 3000 | def |
| 123 | 2012 | 2 | 1500 | def |
| 456 | 2012 | 1 | 2000 | ghi |
| 456 | 2012 | 2 | 2000 | ghi |

View on DB Fiddle

关于SQL:更新 GROUP BY 以包含基于另一列最大值的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52226944/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com