MySQL查询帮助:给出两个不同的结果

时间:2018-03-25 22:18:35

标签: mysql

我的示例数据:http://sqlfiddle.com/#!9/e29e54/7

我的目标是找到已售商品的COUNT和SUM以及引用的商品。

SELECT
clients.`id`,
COUNT(IF(clients.`paid_to_date` != clients.`policy_date`, `premium`, 0)) AS sold_count,
SUM(IF(clients.`paid_to_date` != clients.`policy_date`, `premium`, 0)) AS sold_client,
COUNT(clients.`id`) AS quote_count,
SUM(clients.`premium`) AS quote_client,
users.last_name, users.first_name
FROM `clients`
LEFT JOIN `users` ON `clients`.`user_id` = `users`.`id`
WHERE clients.`policy_date` IN (
    SELECT policy_date FROM clients WHERE month(`policy_date`) = '2' AND year(`policy_date`) = '2018'
)
GROUP BY `users`.`last_name`
ORDER BY users.`id` ASC;

sold_count和quote_count返回相同的数字3,好像“clients。paid_to_date!= clients。policy_date”无法正常工作。对于user_id = 1,John Smith,它应返回2个结果。

此查询为用户返回1个结果:

SELECT  id, client_number, policy_number, agent_name, paid_to_date, policy_date
FROM `clients` WHERE `user_id` = '1' AND month(`policy_date`) = '2'
AND year(`policy_date`) = '2018'
AND `paid_to_date` != `policy_date`
ORDER BY `policy_date` ASC

有关如何使sold_count和sold_clients IF语句正常工作的任何建议将非常感谢!!

我会考虑第一个查询    售出的数量= 2,而不是3。

sold_client正在添加2个结果,但计数不正确。

1 个答案:

答案 0 :(得分:0)

这么简单......我在想什么。这是我的解决方案:

SELECT clients.id,
SUM(IF(clients.`paid_to_date` != clients.`policy_date`, 1, 0)) AS sold_count,
SUM(IF(clients.`paid_to_date` != clients.`policy_date`, `premium`, 0)) AS sold_client,
COUNT(clients.`id`) AS quote_count,
SUM(clients.`premium`) AS quote_client, users.last_name, users.first_name
FROM `clients`
LEFT JOIN `users` ON `clients`.`user_id` = `users`.`id`
WHERE clients.`policy_date` IN (
SELECT policy_date FROM clients WHERE month(`policy_date`) = '2' AND year(`policy_date`) = '2018'
)
GROUP BY users.`last_name`
ORDER BY users.`id` ASC;

更改了第一个SUM()以仅对结果计数求和。