我开始使用这个查询,它给了我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-address
和moves-from-address
之间不同的地址比例。我能够通过使用WHERE
子句成功检查地址差异,该子句检查ia_f.base_street
是否不等于a_f.base_street
(列为invites-from-address
和{{的别名分别为1}}但当我将moves-from-address
子句放在我的WHERE
count
函数中时,它不起作用。是因为我无法在SELECT
或WHERE
函数或两者中放置SELECT
子句吗?尝试将两个调用的结果除以count
子句中的count
函数也存在问题吗?
SELECT
答案 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'