简体   繁体   English

MYSQL选择与SUM不同

[英]MYSQL Select Distinct with SUM

I am developing a Stocks management application, the Portfolio register table has 4 columns, other than date and registry_key, and it looks like this: 我正在开发一个Stocks管理应用程序,Portfolio寄存器表有4列,除了date和Registry_key之外,它看起来像这样:

----------------------------------------
| stock_key | user_key | units | price |
----------------------------------------
| fund_a    | user_1   | 1000  | 100.35|
| fund_c    | user_2   | 4000  | 101.55|
| fund_d    | user_3   | 2000  | 105.65|
| fund_a    | user_1   | 1500  | 101.45|
| fund_b    | user_1   | 500   | 103.35|
----------------------------------------

I wish to select the portfolio of user_1 with distinct stock_key. 我希望选择具有不同stock_key的user_1的投资组合。 For example: 例如:

For user_1 the result should be: 对于user_1,结果应为:

[ 
    {fund_key: "fund_a", units: sum(1000,1500), price: sum(100.35,101.45)},
    {fund_key: "fund_b", units: 500, price: 103.35}
]

Hope the question is understandable. 希望这个问题是可以理解的。 Thanks. 谢谢。

Second Phase 第二阶段

How about I need the price as the aggregate total paid over the number of units. 我需要价格作为支付的总数超过单位数量的价格。 So for user_1 the result would be like: 因此,对于user_1来说,结果将是:

[ 
    {fund_key: "fund_a", units: sum(1000,1500), price: sum(1000*100.35,1500*101.45)/sum(1000,1500)},
    {fund_key: "fund_b", units: 500, price: 103.35}
]

This is important because once the user has brought more units of the same stock at a lower/higher price than before, the accumulated stocks price is averaged out. 这很重要,因为一旦用户以比以前更低/更高的价格带来了更多单位的相同股票,则累计股票价格将被平均。

Thanks. 谢谢。

So try: 因此,请尝试:

SELECT stock_key, SUM(units), SUM(units * price) / SUM(units) 
FROM Portfolio 
WHERE user_key = 'user_1' 
GROUP BY stock_key;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM