具有百分比细分的Mysql子查询(难以查询)

时间:2014-01-27 11:44:45

标签: php mysql sql mysqli

好的我有两个相关的表,其中包含名为'opportunity'的主要字段,另一个包含名为'opportunities_cstm'的附加字段。出于我们的目的,商机表包含以下字段:id和sales_stage。 opportunities_cstm表包含字段id_c和sales_stage_before_closed_c。 id_c是两个表的关联。

sales_stage包含1到10之间的值,也包含“Closed Lost”或“Closed Won”。在实际应用中,1到10表示百分比范围从0-9%到90-99%,封闭损失为0%,关闭赢得为100%。

sales_stage_before_closed_c是它关闭前的百分比范围。

因此,在我的实际查询中,我需要显示每个sales_stage的百分比,显示有多少机会达到了这个阶段并导致获胜机会以及有多少人达到此阶段并导致丢失。

更新到更接近我需要的新查询:

SELECT opportunities_c_top.sales_stage_before_closed_c AS 'Sales Stage',
COUNT(*) * 100.0 /
( SELECT COUNT(*)
FROM `opportunities_cstm` opportunities_cstm join 
`opportunities` opportunities
on opportunities_cstm.id_c = opportunities.id WHERE opportunities.`sales_stage` =   'Closed Won' AND opportunities_cstm.sales_stage_before_closed_c = opportunities_c_top.sales_stage_before_closed_c ) AS 'Closed Won',

COUNT(*) * 100.0 /
( SELECT COUNT(*)
FROM `opportunities_cstm` opportunities_cstm join 
`opportunities` opportunities
on opportunities_cstm.id_c = opportunities.id WHERE opportunities.`sales_stage` =   'Closed Lost' AND opportunities_cstm.sales_stage_before_closed_c = opportunities_c_top.sales_stage_before_closed_c ) AS 'Closed Lost'

FROM `opportunities_cstm` opportunities_c_top join 
`opportunities` opportunities_top
on opportunities_top.id = opportunities_c_top.id_c
WHERE (opportunities_top.`sales_stage` = 'Closed Won' OR opportunities_top.`sales_stage` = 'Closed Lost')  
GROUP BY opportunities_c_top.sales_stage_before_closed_c

http://sqlfiddle.com/#!2/ac28d/1

但它仍然不是100%正确,如果你运行查询它显示60%-69%为200而不是每一方50.

1 个答案:

答案 0 :(得分:0)

SQL并不是真的用于演示。我会考虑提取原始数据然后在PHP中操作它。

SELECT 
    opportunities.`sales_stage`,
    opportunities_cstm.`percent_before_closed_c`,
    count(*)
FROM `opportunities` opportunities join 
    `opportunities_cstm` opportunities_cstm
    on opportunities.id = opportunities_cstm.id_c
WHERE opportunities.`sales_stage` in ('Closed Lost', 'Closed Won')
GROUP BY opportunities.`sales_stage`, opportunities_cstm.`percent_before_closed_c`

除非我完全忽略了这一点。