laravel - 分组行不包括在案例中使用的列
问题描述
我正在构建一个小型股票/投资组合跟踪器,但在检索和计算交易单元格时遇到了一些麻烦。您可以在下面找到transactions
我的数据库表中的虚拟数据。
// Transactions table
ID | Name | Symbol | Currency | amount_bought | amount_sold | price | commission | bought | portfolio_id
_____________________________________________________________________________________________________________________
1 | Ocugen Inc | FRA.2H51 | EUR | 55 | NULL | 0.29 | 7.51 | 1 | 1
2 | Tesla, Inc | NASDAQ.TSLA | EUR | 5 | NULL | 654.87 | 4.23 | 1 | 1
3 | Ocugen Inc | FRA.2H51 | EUR | NULL | 40 | 1.31 | 7.55 | 0 | 1
我正在使用一个名为bought
(最后一列)的布尔值来“识别”我的交易是卖出股票还是买入股票。接下来,我想使用 my 检索我的所有交易portfolio_id
并将它们分组到他们的name
,symbol
并currency
输出以下内容:
// Desired result:
Name | Symbol | Currency | amount_current | commission_total | bought_total | sales_total
_____________________________________________________________________________________________________
Ocugen Inc | FRA.2H51 | EUR | 15 | 15.06 | 15.95 | 52.4
Tesla, Inc | NASDAQ.TSLA | EUR | 5 | 4.23 | 3274.35 | 0
目前我的代码和我想要的完全一样,除了我的行是如何分组的。因为我使用的是case
,为了计算单只股票的买卖总额,我不得不将该bought
列包含在我的groupBy()
. bought
因此,除了name
,symbol
和之外,我的结果也被分组currency
:
// Current result:
name | symbol | currency | amount_current | commission_total | bought_total | sales_total
_____________________________________________________________________________________________________
Ocugen Inc | FRA.2H51 | EUR | 15 | 7.51 | 15.95 | 0
Tesla, Inc | NASDAQ.TSLA | EUR | 5 | 4.23 | 3274.35 | 0
Ocugen Inc | FRA.2H51 | EUR | NULL | 7.55 | 0 | 52.4
您可以在下面找到生成上述结果的代码。
$transactions = Transaction::where('portfolio_id', $portfolio->id)
->groupBy('name', 'symbol', 'currency', 'bought')
->select([
'name',
'symbol',
'currency',
DB::raw('sum(amount_bought) - sum(amount_sold) as amount_current'),
DB::raw('sum(commission) AS commission_total'),
DB::raw('case when bought = 1 then sum(price) * sum(amount_bought) else 0 end as bought_total'),
DB::raw('case when bought = 0 then sum(price) * sum(amount_sold) else 0 end as sales_total')
])
->get();
如何将我的交易分组到 stock name
,symbol
并currency
计算它们的总数而不将它们分组到bought
列上?
解决方案
我真的不知道 Laravel,但你应该能够使用:
$transactions = Transaction::where('portfolio_id', $portfolio->id)
->groupBy('name', 'symbol', 'currency')
->select([
'name',
'symbol',
'currency',
DB::raw('sum(amount_bought) - sum(amount_sold) as amount_current'),
DB::raw('sum(commission) AS commission_total'),
DB::raw('sum(case when bought = 1 then price * amount_bought else 0 end as bought_total'),
DB::raw('sum(case when bought = 0 then price * amount_sold) else 0 end) as sales_total')
])
->get();
也就是说,bought
从 中删除group by
并将case
参数设置为sum()
。
推荐阅读
- azure - 访问 Azure 云服务上的特定 Web 角色节点
- python - Snakemake - 在进入下一个“批次”之前运行给定通配符的所有规则
- dynamics-crm - Dynamics CE 365 上的全渠道销售
- reactjs - 根据布尔值反应更新道具和渲染
- scikit-learn - 在 Sagemaker 中加载拟合管道模型以进行推理
- android - 在服务器上监听 socket.io 时,Android 上使用了哪些端口
- git - git rebase interractive 在与冲突合并之前
- c# - 如何在搜索引擎中隐藏 doc 文件
- cordova - 科尔多瓦的蓝牙 BLE 信标
- java - 蓝牙扫描失败 - Android