我的SQL请求需要一些帮助。我有这张桌子:
CREATE TABLE `contact` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`first_name` varchar(65) DEFAULT NULL,
`last_name` varchar(65) DEFAULT NULL,
`phonenumber` varchar(45) NOT NULL,
`avinumber` varchar(45) DEFAULT NULL,
`date` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`source` varchar(45) NOT NULL,
`nbrtryies` int(11) NOT NULL DEFAULT '0',
`treaty_at` date DEFAULT NULL,
`comment` varchar(255) DEFAULT '',
`status` varchar(45) DEFAULT 'KO',
`campagne_id` int(11) NOT NULL,
`treated_by` int(11) DEFAULT NULL,
`nodetree_id` int(11) DEFAULT NULL,
`avi` varchar(45) DEFAULT NULL,
`sessionid` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id_UNIQUE` (`id`),
KEY `fk_contact_campagne1_idx` (`campagne_id`),
KEY `fk_contact_agent1_idx` (`treated_by`),
CONSTRAINT `fk_contact_agent` FOREIGN KEY (`treated_by`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `fk_contact_campagne1` FOREIGN KEY (`campagne_id`) REFERENCES `campagne` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=82 DEFAULT CHARSET=latin1;
我需要计算列数时的行数和行数:
treated_by
具有特定值,并按该列
对结果进行分组Thsi就是我所做的,但我似乎没有工作:
SELECT
co.treated_by AS userId,
COUNT(*) AS treated,
SUM(CASE WHEN ca.userId=1 THEN 1 ELSE 0 END) AS total
FROM
contact AS co
INNER JOIN
campagne AS ca ON ca.id = co.campagne_id
WHERE
(co.date BETWEEN '2013-07-09' AND '2014-08-15')
AND co.treated_by IN (2 , 40)
GROUP BY co.treated_by
这就是我得到的:
----------------------------
| userId | treated | total |
----------------------------
| 2 | 5 | 5 |
----------------------------
| 40 | 3 | 3 |
----------------------------
我需要这样的东西:
----------------------------
| userId | treated | total |
----------------------------
| 2 | 5 | 20 |
----------------------------
| 40 | 3 | 20 |
----------------------------
非常感谢你的帮助
答案 0 :(得分:0)
GROUP BY co.treated_by,它产生记录COUNT(*)AS处理5和3,所以SUM(CASE WHEN ca.userId = 1 THEN 1 ELSE 0 END)AS总计,不可能超过20和20。
答案 1 :(得分:0)
如果条件是co.treated_by
,那么为什么逻辑包含ca.userId
?
也许这会奏效:
SELECT co.treated_by AS userId,
COUNT(*) AS treated,
SUM(co.treated_by) AS total
FROM contact co INNER JOIN
campagne ca
ON ca.id = co.campagne_id
WHERE (co.date BETWEEN '2013-07-09' AND '2014-08-15') AND
co.treated_by IN (2 , 40)
GROUP BY co.treated_by;
请注意,我还使用MySQL支持的更简单版本替换了total
的计算。