mysql子选择新手

时间:2012-08-09 04:29:59

标签: mysql select subquery

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    leadcount   losscount
1           Queensland  7            0
8           Victoria    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

任何帮助都是适当的

1 个答案:

答案 0 :(得分: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列是不可预测的。根据你所说的,我怀疑你真的想要它。