【发布时间】:2019-11-28 03:13:06
【问题描述】:
在 Laravel 应用程序上工作,我需要从第二个数据库中检索数据,这就是为什么我有一个像这样的特殊“DB”:
DB::connection('sqlsrv2')。
在这个数据库中,有一个表 customerAccount 和一个表 Opportunity。
我们想知道我们每个月创造了多少机会,赢得或失去了多少机会,以及为一个精确的年份和一个精确的客户家庭。
我可以通过一些 foreach 和每个案例的查询来检索数据(新的、赢得或失去的机会),但最终每个客户和每个月都会有超过 12700 个查询。
所以我想到了 SQL SUM,并且我可以在一个 (looong) 查询中完成它,该查询将创建 3 列(新、赢、丢失)。然后我会为所选年份的每个月重复查询。 问题是,我不记得该怎么做,也找不到任何帮助,因为我真的不知道要搜索什么。
这是我写查询的错误尝试:[编辑以遵循评论中的建议]
$clients = DB::connection('sqlsrv2')->table('customerAccount')
->select(DB::connection('sqlsrv2')->raw(
"customerAccount.Name,
SUM(case when opportunity.customerAccountId = customerAccount.Id
and YEAR(opportunity.OpportunityDate) = $year
and MONTH(opportunity.OpportunityDate) = $month
then 1
else 0
end) as nbOppNew,
SUM(case when opportunity.customerAccountId = customerAccount.Id
and YEAR(opportunity.OpportunityCloseDate) = $year
and MONTH(opportunity.OpportunityCloseDate) = $month
and StageProbability = 99
then 1
else 0
end) as nbOppWon,
SUM(case when opportunity.customerAccountId = customerAccount.Id
and YEAR(opportunity.OpportunityCloseDate) = $year
and MONTH(opportunity.OpportunityCloseDate) = $month
and StageProbability <= 1
then 1
else 0
end) as nbOppLost
FROM
customerAccount
INNER JOIN opportunity ON customerAccount.Id = opportunity.customerAccountId
WHERE
MainInvoicingAddress_CountryIsoCode = 'ES'
and familyId = '$family'
GROUP BY customerAccount.Name"
))
->get();
Laravel 产生的错误:SQLSTATE[42000]: [Microsoft][SQL Server Native Client 11.0][SQL Server]Incorrect syntax near 'from'.
我真正想要的是一个带有客户名称的数组,并且对于每个:第二个名为“nbOppNew”的条目,其中包含 SUM 值。第三个是“nbOppWon”,第四个是“nbOppLost”。
【问题讨论】:
-
您希望如何用日期(然后是机会.OpportunityCloseDate)值求和?
-
我没有,我想总结案件发生的次数。我应该用
then 1替换then opportunity.OpportunityDate吗? -
是的。您应该将日期替换为值 1
-
我不确定
raw方法是否支持将 PHP 变量作为 SQL 语句的一部分。将 $year 更改为'$year'($month和$family)或使用占位符使用参数化查询。
标签: sql sql-server laravel-5 sum