使用Mysql比较数据

时间:2017-06-12 14:34:42

标签: mysql

我有一个服务表,我需要列出时间,并且同一客户要求提供3种类型的服务。 (ServiceA,serviceB,serviceC)

在低级示例中,我已经有两种服务类型,但我尝试添加第三种服务,但我不能。

很抱歉,其他任何非常重要的事情,我忘了提及我是如何得到每个服务在该列表上完成的日期的?

SELECT * 
FROM service 
WHERE status = 'CONCLUDED' AND (
   CASE WHEN service = 'servicoC' THEN 
   (CASE WHEN data LIKE '2017-05%' THEN 1 ELSE 0 END) ELSE data END) AND servico IN ' ServiceB ') 
GROUP BY id_client HAVING MIN (service) ='servicoA'AND MAX (service) ='servicoB'

表:

Id;
Id client
service;
date;
Status;

结果Ex:

Id_client,date_serviceA,date_serviceB,date_serviceC

1 个答案:

答案 0 :(得分:0)

您可以使用GROUP_BYHAVING来执行此操作,例如:

SELECT id_client, COUNT(*)
FROM service
WHERE service IN ('ServiceA', 'ServiceB', 'ServiceC')
GROUP BY id_client
HAVING COUNT(DISTINCT service)) >= 3;

如果您需要按服务计算,则可以将其添加到GROUP BYSELECT,例如:

SELECT id_client, service, COUNT(*)
FROM service
WHERE service IN ('ServiceA', 'ServiceB', 'ServiceC')
GROUP BY id_client, service
HAVING COUNT(DISTINCT service)) >= 3;

<强>更新

如果您想要每个服务的最长日期,那么您可以使用内部SELECT查询来执行此操作,例如:

SELECT s.id_client, s.service, COUNT(s.*),
(SELECT MAX(date) FROM service where id_client = s.id_client and service = 'ServiceA') AS "date_ServiceA",
(SELECT MAX(date) FROM service where id_client = s.id_client and service = 'ServiceB') AS "date_ServiceB",
(SELECT MAX(date) FROM service where id_client = s.id_client and service = 'ServiceC') AS "date_ServiceC"
FROM service s
WHERE s.service IN ('ServiceA', 'ServiceB', 'ServiceC')
GROUP BY s.id_client, s.service
HAVING COUNT(DISTINCT s.service)) >= 3;