我只想问是否可以对具有相同值但来自不同列的行进行分组。
我有一种情况,如果发现记录为“连续”交易,我们应该通过检查 STARTDATETIME 列是否与以前的数据 ENDDATETIME 相匹配来汇总总分钟数列是否相同。请参阅下面的图像链接以供参考。
谢谢大家。
答案 0 :(得分:0)
我修改了戈登·利诺夫(Gordon Linoff)的solution(请参阅问题下方的评论):
SELECT
c.employee_id
,MIN(c.start_date) AS start_date
,MAX(c.end_date) AS end_date
,COUNT(*) AS numcontracts,
TIMESTAMPDIFF(minute,MIN(c.start_date),MAX(c.end_date)) AS timediff
FROM
(
SELECT
c0.*
,(@rn := @rn + COALESCE(startflag, 0)) AS cumestarts
FROM
(SELECT c1.*,
(NOT EXISTS (SELECT 1
FROM contracts c2
WHERE c1.employee_id = c2.employee_id AND
c1.start_date = c2.end_date
)
) AS startflag
FROM contracts c1
ORDER BY employee_id, start_date
) c0 CROSS JOIN (SELECT @rn := 0) params
) c
GROUP BY c.employee_id, c.cumestarts
http://rextester.com/VOGMU19779
timediff
包含组合时间间隔中经过的分钟数。