显示总和的最大值
我试图找到总和结果的最大值,但我也找不到显示日期的方法。 我有一个表 transactions,其中包含如下数据:
transaction_date--Transaction_agent_id--transaction_amount
2/5/11 321 20
2/5/11 321 10
2/5/11 400 100
3/5/11 321 5
3/5/11 345 100
3/5/11 321 10
3/5/11 345 50
4/5/11 345 80
4/5/11 321 5
我想要的结果是这样
transaction_date--Transaction_agent_id--transaction_amount
2/5/11 321 30
2/5/11 400 100
3/5/11 345 150
它应该做的是首先将每个 agent_id 每天的所有金额相加,然后向我显示该代理的最佳日期。
我所做的是这
SELECT a.transaction_agent_id, max(a.stotal) FROM
(
SELECT transaction_date,transaction_agent_id, sum(transaction_amount) as 'Stotal' FROM transactions
GROUP BY transaction_agent_id, transaction_date
)a
GROUP BY a.transaction_agent_id
给了我这个,
Transaction_agent_id--transaction_amount
321 30
400 100
345 150
这是正确的,但我无法添加 transaction_date。
更新:我刚刚解决了。好吧,如果有人想要解决方案,那就是这里。
SELECT a.transaction_date, a.transaction_agent_id, max(a.stotal) FROM
(
SELECT row_number() over (partition by transaction_agent_id order by sum(transaction_amount)desc) AS 'roww' ,transaction_date,transaction_agent_id, sum(transaction_amount) as 'Stotal' FROM transactions
GROUP BY transaction_agent_id, transaction_date
) a
WHERE a.roww = 1
GROUP BY a.transaction_date, a.transaction_agent_id, a.roww
感谢大家的意见。
i am trying to find the max values of a sum result but i can not find a way to show the date too.
i have a table transactions which has data like this:
transaction_date--Transaction_agent_id--transaction_amount
2/5/11 321 20
2/5/11 321 10
2/5/11 400 100
3/5/11 321 5
3/5/11 345 100
3/5/11 321 10
3/5/11 345 50
4/5/11 345 80
4/5/11 321 5
what i want the result to be is this
transaction_date--Transaction_agent_id--transaction_amount
2/5/11 321 30
2/5/11 400 100
3/5/11 345 150
What it should do is first of all to sum all the amount per agent_id, per day and then to show me the best day of that agent.
What i have done is this
SELECT a.transaction_agent_id, max(a.stotal) FROM
(
SELECT transaction_date,transaction_agent_id, sum(transaction_amount) as 'Stotal' FROM transactions
GROUP BY transaction_agent_id, transaction_date
)a
GROUP BY a.transaction_agent_id
which gives me this
Transaction_agent_id--transaction_amount
321 30
400 100
345 150
which is correct but i can not add the transaction_date.
Update: I just solved it. Well if anyone wants the solution here it is.
SELECT a.transaction_date, a.transaction_agent_id, max(a.stotal) FROM
(
SELECT row_number() over (partition by transaction_agent_id order by sum(transaction_amount)desc) AS 'roww' ,transaction_date,transaction_agent_id, sum(transaction_amount) as 'Stotal' FROM transactions
GROUP BY transaction_agent_id, transaction_date
) a
WHERE a.roww = 1
GROUP BY a.transaction_date, a.transaction_agent_id, a.roww
Thank you all for your input.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
SQL语句
测试脚本
SQL Statement
Test script
只需在外部选择中按
transaction_date
进行分组即可:Just group by
transaction_date
in the outer select as well: