有一个查询,我想得到:
Username
与每个机会记录相关联的
Sales Stage
Dollar
金额
我想:
当前查询:
$sql = "SELECT u.user_name as USER,
if(o.sales_stage='Prospecting', o.amount, '') as PROSPECTING,
if(o.sales_stage='Needs Analysis', o.amount, '') as NEEDS_ANALYSIS,
if(o.sales_stage='Closed Won', o.amount, '') as CLOSED_WON
FROM opportunities o,
users u
WHERE o.assigned_user_id = u.id
GROUP BY u.user_name ";
当前结果:
USER PROSPECTING NEEDS_ANALYSIS CLOSED_WON
---------------------------------------------
chris 10000 0 0
chris 0 15000 0
chris 0 0 10000
sara 5000 0 0
sara 0 0 10000
我想要做的是折叠结果,我只获得1个用户,以及每个SalesStage的相应金额
USER PROSPECTING NEEDS_ANALYSIS CLOSED_WON
---------------------------------------------
chris 10000 15000 10000
sara 5000 0 10000
答案 0 :(得分:4)
“折叠”通常称为“旋转”,因为您将行转换为柱状数据。使用:
SELECT u.user_name as USER,
MAX(CASE WHEN o.sales_stage = 'Prospecting' THEN o.amount END) AS PROSPECTING,
MAX(CASE WHEN o.sales_stage = 'Needs Analysis' THEN o.amount END) AS NEEDS_ANALYSIS,
MAX(CASE WHEN o.sales_stage = 'Closed Won' THEN o.amount END) AS CLOSED_WON
FROM OPPORTUNITIES o
JOIN USERS u ON u.id = o.assigned_user_id
GROUP BY u.user_name
答案 1 :(得分:1)
您需要将聚合函数添加到$ amount ...即:
SELECT
u.user_name as USER,
if(o.sales_stage='Prospecting', SUM(o.amount), '') as PROSPECTING,
if(o.sales_stage='Needs Analysis', SUM(o.amount), '') as NEEDS_ANALYSIS,
if(o.sales_stage='Closed Won', SUM(o.amount), '') as CLOSED_WON
FROM
opportunities o,
users u
WHERE
o.assigned_user_id = u.id
GROUP BY
u.user_name
修改强>
现在我考虑一下,你可能仍会得到单独的行,因为同一用户的记录中的销售阶段可能不同。您是否考虑过使用例程对每个销售阶段进行计算,以便将结果折叠为每个用户一行?
答案 2 :(得分:0)
您可以将当前查询包装在另一个查询中,如下所示:
select subquery.user,
sum(subquery.propspecting),
sum(subquery.needs_analysis),
sum(subquery.closed_won)
from (*...your query goes here*) subquery
group by subquery.user