我想知道是否有办法在不影响计数列的情况下过滤结果。我有订单,员工和服务表。我有一个查询,显示员工完成的服务,计算每项服务的员工数量,并计算每个服务的每位员工的价格。我想做的是仅过滤掉特定员工完成的服务,但保持员工人数相同。以下查询显示了我想要的内容,但每当我向WHERE子句添加员工ID时,员工数量显然会降至1。
SELECT R.`order_id`, R.`service_id`, S.`name` AS 'service_name', Rprice.`price` AS 'service_price', COUNT(R.`employee_id`) AS 'number_employees', ROUND(Rprice.`price` / COUNT(R.`employee_id`), 2) AS 'price_employee_service' FROM `R_services_employees_orders` R
JOIN `R_order_service_price` Rprice ON R.`order_id` = Rprice.`order_id` AND R.`service_id` = Rprice.`service_id`
JOIN `Employees` E ON R.`employee_id` = E.`id`
JOIN `Orders` O on R.`order_id` = O.`id`
JOIN `Services` S on R.`service_id` = S.`id`
WHERE NOT E.`department` = 'o'
AND O.`completed` BETWEEN '2017-04-26' AND '2017-05-06'
GROUP BY R.`order_id`, R.`service_id`
ORDER BY R.`order_id`, R.`service_id`;
我尝试过使用子查询,但似乎无法获得正确的查询。提前谢谢。
表格结构如下
CREATE TABLE `Employees` (
`id` varchar(3) NOT NULL DEFAULT '',
`name` varchar(50) DEFAULT NULL,
`department` varchar(1) DEFAULT NULL COMMENT 'Enter P R or M',
`active` tinyint(1) DEFAULT '1',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `Orders` (
`id` int(11) unsigned NOT NULL,
`completed` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `R_order_service_price` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`order_id` int(11) unsigned DEFAULT NULL,
`service_id` varchar(6) DEFAULT NULL,
`price` float DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `FK_order_price` (`order_id`),
KEY `FK_service_price` (`service_id`),
CONSTRAINT `FK_order_price` FOREIGN KEY (`order_id`) REFERENCES `Orders` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `FK_service_price` FOREIGN KEY (`service_id`) REFERENCES `Services` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `R_services_employees_orders` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`order_id` int(11) unsigned DEFAULT NULL,
`employee_id` varchar(3) DEFAULT NULL,
`service_id` varchar(6) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `FK_order` (`order_id`),
KEY `FK_service` (`service_id`),
KEY `FK_employee` (`employee_id`),
CONSTRAINT `FK_employee` FOREIGN KEY (`employee_id`) REFERENCES `Employees` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `FK_order` FOREIGN KEY (`order_id`) REFERENCES `Orders` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `FK_service` FOREIGN KEY (`service_id`) REFERENCES `Services` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
答案 0 :(得分:0)
您可以在选择中使用CASE语句,例如:
width=n
您可以通过这种方式汇总任何员工特定的衡量标准,以便在正常计算中保持整体汇总。