如何计算where子句的结果以便计算MYSQL select子句的比例?

时间:2016-04-28 21:03:45

标签: mysql select subquery

我开始使用这个查询,它给了我8条带有“已声明”状态的记录。我想查看invites-from-address列中的任何地址是否与moves-from-address列中的地址不同:

SELECT i.id, i.company_id, i.status,  
  ia_f.base_street as "invites-from-address", a_f.base_street as "moves-from-address", 
  ia_t.base_street as "invites-to-address", a_t.base_street as "moves-to-address", i.`mover_first_name`, 
  i.mover_last_name, i.`to_address_id`

FROM invites i
JOIN moves m ON i.id = m.`claimed_invite_id`
JOIN `invite_addresses` ia_f ON ia_f.id = i.`from_address_id`
JOIN addresses a_f ON a_f.id = m.from_address_id

JOIN `invite_addresses` ia_t ON ia_t.id = i.to_address_id
JOIN addresses a_t ON a_t.id = m.to_address_id

WHERE i.`company_id` = 1040345
GROUP BY id

我在下面的查询中尝试做的是动态创建average_discrepancy列,显示invites-from-addressmoves-from-address之间不同的地址比例。我能够通过使用WHERE子句成功检查地址差异,该子句检查ia_f.base_street是否不等于a_f.base_street(列为invites-from-address和{{的别名分别为1}}但当我将moves-from-address子句放在我的WHERE count函数中时,它不起作用。是因为我无法在SELECTWHERE函数或两者中放置SELECT子句吗?尝试将两个调用的结果除以count子句中的count函数也存在问题吗?

SELECT

1 个答案:

答案 0 :(得分:1)

您需要将其放入SUM而不是COUNT。像这样的东西可以解决这个问题:

 SELECT i.id, i.company_id, i.status, 
  SUM(CASE WHEN ia_f.base_street != a_f.base_street THEN 1 ELSE 0 END)/ SUM(CASE WHEN i.status='claimed' THEN 1 ELSE 0 END) as 'average_discrepancy', 
  ia_f.base_street as 'invites-from-address', 
  a_f.base_street as 'moves-from-address', 
  ia_t.base_street as 'invites-to-address', 
  a_t.base_street as 'moves-to-address',
  i.mover_first_name, 
  i.mover_last_name, 
  i.to_address_id

FROM invites i
JOIN moves m ON i.id = m.claimed_invite_id
JOIN invite_addresses ia_f ON ia_f.id = i.from_address_id
JOIN addresses a_f ON a_f.id = m.from_address_id

JOIN invite_addresses ia_t ON ia_t.id = i.to_address_id
JOIN addresses a_t ON a_t.id = m.to_address_id

WHERE i.company_id = 1040345

AND i.status = 'claimed'