如果仅当当前字段存在于数组中时如何计算或求和字段
Posted
技术标签:
【中文标题】如果仅当当前字段存在于数组中时如何计算或求和字段【英文标题】:How to count or sum fields if only if the current field exists in an array 【发布时间】:2018-02-08 21:24:11 【问题描述】:我有以下疑问:
SELECT
count(form_rows.field_name),
form_rows.field_name,
sum(form_rows.field_value) as sales,
form_Submissions.id as fsId
FROM form_submissions
LEFT JOIN form_rows on form_Submissions.id = form_rows.form_submission_id
WHERE form_submissions.organization_id = 10
GROUP BY form_rows.field_name
这会重现以下结果:
问题:有没有办法根据field_name
SUM
和COUNT
澄清:
假设我有一个数组:["ssn", "price"]
我只想对sales
求和,即field_names
存在于给定数组中
【问题讨论】:
【参考方案1】:这样不行吗:
SELECT
count(form_rows.field_name),
form_rows.field_name,
sum(form_rows.field_value) as sales,
form_Submissions.id as fsId
FROM form_submissions
LEFT JOIN form_rows on form_Submissions.id = form_rows.form_submission_id
WHERE form_submissions.organization_id = 10
AND form_rows.field_names in ('ssn','price')
GROUP BY form_rows.field_name
【讨论】:
太棒了,我完全忘记了那个选项!因为这只是怪物查询中的一个子查询。以上是关于如果仅当当前字段存在于数组中时如何计算或求和字段的主要内容,如果未能解决你的问题,请参考以下文章