0
SELECT a.lead_id, c.state_name AS COL1DATA, count( c.state_name ) AS leadcount, (

SELECT count( won_loss ) AS wonlosscount
FROM lead_status
WHERE (won_loss = 'loss')
AND lead_id = a.lead_id
) AS losscount
FROM lead AS a
JOIN states AS c ON a.state_id = c.states_id
GROUP BY c.state_name
ORDER BY losscount DESC

我得到的答案是

Lead_id COL1DATA 线索计数 losscount
1 昆士兰 7 0
8 维多利亚 3 0

领先地位

lead_id     won_loss    won_price   won_mainreason  loss_mainreason     loss_attachment_id  lost_dont_sell_note     add_note    dealer_satisfaction
      5     win         4655        pricing                                                                         fghfg       somewhat
      8     won         34543       pricing                                                                         sfdgs       satisfied
      7     loss                                    service                                                         Additional Notes    verygood
      9     loss                                    not_in_stock                                                    Additi      satisfied

但损失计数应该是 1 和 1

有任何帮助

4

1 回答 1

0

我猜想在 state_name 上分组的同时在相关查询中混合非聚合的lead_id 存在问题。也许你可以描述你想要回来的东西。

编辑:基于下面评论中的 OP 反馈。

编辑 2:更改为基于聊天会话的左外连接。并非所有潜在客户都有lead_status。

SELECT
    s.state_name AS COL1DATA, count(c.state_name) AS leadcount,
    sum(case when ls.won_loss = 'loss' then 1 else 0 end) as losscount
FROM
    lead AS l
    INNER JOIN states AS s ON s.state_id = l.states_id
    LEFT OUTER JOIN lead_status as ls on ls.lead_id = l.lead_id
GROUP BY s.state_name
ORDER BY losscount DESC

我可能会争辩说这个版本稍微好一点。但我不想完全改变你的查询。(我确实更改了别名,因为 A 和 C 令人困惑。)

SELECT
    min(s.state_name) AS COL1DATA,
    count(l.lead_id) AS leadcount, /* counting non-nullable key on the outer side */
    sum(case when ls.won_loss = 'loss' then 1 else 0 end) as losscount
FROM
    lead AS l
    INNER JOIN states AS s ON s.state_id = l.states_id
    LEFT OUTER JOIN lead_status as ls on ls.lead_id = l.lead_id
GROUP BY s.state_id /* might be better to group on the id */
ORDER BY losscount DESC

您在输出中包含的lead_id 列是不可预测的,除非该组只有一行。根据你所说的,我怀疑你真的想要它。

于 2012-08-09T04:49:00.310 回答