合并两个 SOQL 查询

Posted

技术标签:

【中文标题】合并两个 SOQL 查询【英文标题】:Combine two SOQL queries 【发布时间】:2013-06-04 09:11:57 【问题描述】:

我是 SOQL 的初学者,希望你能帮助我。 我想结合这两个查询:

查询 1:

SELECT Id, Category__c, Segment__c
FROM Account
WHERE (Category__c = 'Prospect' AND Segment__c = 'High') OR (Category__c = 'Referrer' AND Segment__c = 'High')

查询 2:

SELECT Account_vod__c, WEEK_IN_YEAR(Call_Date_vod__c), CALENDAR_YEAR(Call_Date_vod__c)
FROM Call2_vod__c
WHERE Call_Date_vod__c = LAST_N_WEEKS:7
GROUP BY Account_vod__c, Call_Date_vod__c

Account 的 id 应该等于 Call2_vod__c 中的 Account_vod__c 值。

当我将这些结合起来时,我得到的结果是:

组合查询:

SELECT Id, Category__c, Segment__c
FROM Account
WHERE id in (select Account_vod__c from Call2_vod__c where Call_Date_vod__c = LAST_N_WEEKS:7) AND ((Category__c = 'Prospect' AND Segment__c = 'High') OR (Category__c = 'Referrer' AND Segment__c = 'High'))

但现在我缺少周和年值:

WEEK_IN_YEAR(Call_Date_vod__c), CALENDAR_YEAR(Call_Date_vod__c)

这部分: GROUP BY Account_vod__c,Call_Date_vod__c

如何组合这些查询并显示正确的星期和日历数据?

谢谢!

【问题讨论】:

顺便说一句,Stackexchange 上有一个额外的 Salesforce 论坛:salesforce.stackexchange.com 【参考方案1】:

如果您的 Account_vod__c 是对 Account 对象的查找,您可以通过键入 Account_vod__r.Name 等(使用“r”而不是“c”并使用点)从 Account 获取字段。

那么试试这样的东西?

SELECT Account_vod__c, Account_vod__r.Category__c, Account_vod__r.Segment__c, WEEK_IN_YEAR(Call_Date_vod__c), CALENDAR_YEAR(Call_Date_vod__c)
FROM Call2_vod__c
WHERE Call_Date_vod__c = LAST_N_WEEKS:7
GROUP BY Account_vod__c, Account_vod__r.Category__c, Account_vod__r.Segment__c, WEEK_IN_YEAR(Call_Date_vod__c), CALENDAR_YEAR(Call_Date_vod__c)

一个类似的,应该适用于没有你的对象的每个人:

SELECT AccountId, Account.Name, COUNT(Id) countOfContactsCreatedThatWeek, WEEK_IN_YEAR(CreatedDate) week, CALENDAR_YEAR(CreatedDate) year
FROM Contact
GROUP BY AccountId, Account.Name, WEEK_IN_YEAR(CreatedDate), CALENDAR_YEAR(CreatedDate)

【讨论】:

【参考方案2】:

如果您可以使用两个查询,我会从它开始。在您拥有的组合版本中,无论如何,您在技术上都调用了两个查询。 where 子句中的内部查询算作针对您的调控器限制的第二次查询。

如果您使用的是 Apex,请尝试:

Map<Id, Account> aMap = new Map<Id, Account>([SELECT Id, Category__c, Segment__c
FROM Account
WHERE (Category__c = 'Prospect' AND Segment__c = 'High') OR (Category__c = 'Referrer' AND Segment__c = 'High')]);

List<Call2_vod__c> callList = [SELECT Account_vod__c, WEEK_IN_YEAR(Call_Date_vod__c), CALENDAR_YEAR(Call_Date_vod__c)
FROM Call2_vod__c
WHERE Call_Date_vod__c = LAST_N_WEEKS:7 and Id in :aMap.keySet()
GROUP BY Account_vod__c, Call_Date_vod__c];

【讨论】:

第二个将是AggregateResult,它有自己的一系列小问题。

以上是关于合并两个 SOQL 查询的主要内容,如果未能解决你的问题,请参考以下文章

合并两个查询以获取 SQL 中的合并值

mybatis查询结果如何合并为列表

sql 用union合并合并查询结果

将两个查询合并为一个查询

在两个键上加入/合并两个查询集

mysql合并结果集