我需要能够对一列(小时)求和,它与其他列中的几个条件匹配。这就是表格的样子。
payrollid, agentid, ptid, serviceid, dateincurred ,hours
209 , 284 , 580 , 1320 , '2014-05-19' ,4
209 , 284 , 569 , 1433 , '2014-45-19' ,2
209 , 284 , 580 , 1433 , '2014-05-19' ,2
209 , 284 , 569 , 1433 , '2014-05-19' ,2
209 , 284 , 580 , 1320 , '2014-05-19' ,7
209 , 284 , 580 , 19 , '2014-05-20' ,1
209 , 284 , 569 , 1318 , '2014-45-21' ,2
209 , 284 , 580 , 1320 , '2014-45-22' ,1
209 , 284 , 580 , 16 , '2014-05-23' ,1
209 , 284 , 569 , 1445 , '2014-45-24' ,9
209 , 284 , 580 , 1427 , '2014-05-25' ,1
209 , 284 , 569 , 1326 , '2014-05-28' ,1
209 , 284 , 569 , 1445 , '2014-45-29' ,4
209 , 284 , 569 , 1320 , '2014-05-29' ,1
209 , 284 , 569 , 1347 , '2014-45-29' ,5
209 , 284 , 580 , 1320 , '2014-05-30' ,1
209 , 284 , 569 , 1347 , '2014-05-30' ,5
209 , 284 , 580 , 1326 , '2014-05-31' ,1
209 , 284 , 580 , 1348 , '2014-06-01' ,1
209 , 284 , 580 , 24 , '2014-06-01' ,1
查询如下所示:
SELECT
p.agentid,
p.ptid,
p.dateincurred,
p.serviceid,
(
SELECT
GROUP_CONCAT(p.hours)
FROM payroll_detail_temp p3
WHERE p3.payrollid = '209'
AND (
p3.dateincurred BETWEEN '2014-05-19'
AND DATE_ADD('2014-05-19', INTERVAL 6 DAY))
AND p3.serviceid = p.serviceid
GROUP BY
p3.serviceid
LIMIT 1
) AS week1,
(
SELECT
GROUP_CONCAT(p2.hours)
FROM
payroll_detail_temp p2
WHERE
p2.payrollid = '209'
AND (
p2.dateincurred BETWEEN '2014-05-25'
AND DATE_ADD('2014-05-25', INTERVAL 6 DAY))
AND p2.serviceid = p.serviceid
GROUP BY
p2.serviceid,
p2.dateincurred
LIMIT 1
) AS week2,
GROUP_CONCAT(p.serviceid) AS services,
GROUP_CONCAT(p.dateincurred) AS dates
FROM
payroll_detail_temp p
INNER JOIN agent ON (p.agentid = agent.id)
INNER JOIN service ON (p.serviceid = service.id)
INNER JOIN payer ON (p.payerid = payer.id)
INNER JOIN prov ON (p.provid = prov.id)
INNER JOIN patient ON (p.ptid = patient.id)
WHERE
p.payrollid = '209'
AND (
p.dateincurred BETWEEN '2014-05-19'
AND DATE_ADD('2014-05-25', INTERVAL 14 DAY)
)
GROUP BY
p.serviceid,
p.dateincurred
第1周和第2周列表示2周工作时间,在本例中为2014-05-19和2014-06-01。因此,Week1列将分组agentid,ptid,serviceid匹配和dateincurred的小时数,范围为2014-05-19到2014-05-25。同样适用于第2周,其中dateincurred在2014-05-26至2014-06-01之间。
我的查询问题是我得到了重复项,就像下面查询结果中显示的最后两个结果一样。 Week1应该有9.00和Week2需要为null;同样在第1周以下的行应为null,第2周为4.00。第5行和第5行也可以看到相同的情况。 6.在第5行,第1周应为7.00,4.00和1.00,第2周应为空。第6行不应该存在。
我知道存在重复项,因为dateincurred字段与查询重叠,但我无法想象它周围的其他任何内容。
答案 0 :(得分:1)
如果您有第一张照片中显示的表格。然后,您可以通过此查询轻松实现所需内容:
SELECT
PAYROLLID,
AGENTID,
PTID,
SERVICEID,
DATEINCURED,
CASE WHEN (DATEINCURRED BETWEEN '2014-05-19' AND '2014-05-25') THEN SUM(HOURS) END WEEK1,
CASE WHEN (DATEINCURRED BETWEEN '2014-05-26' AND '2014-06-01') THEN SUM(HOURS) END WEEK2
FROM
YOUR_TABLE_NAME
GROUP BY
PAYROLLID,
AGENTID;