簡體   English   中英

具有百分比明細的MySQL子查詢(困難查詢)

[英]Mysql sub-query with percentage breakdown (difficult query)

好的,我有兩個相關的表,一個包含稱為“ opportunities”的主要字段,另一個包含名為“ opportunities_cstm”的附加字段。 就我們而言,機會表包含以下字段:id和sales_stage。 careers_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。

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`

除非我完全忽略了這一點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM