I want to create a column in mysql workbench where there is a sum of the duration of a behaviour when multiple columns (eg condition, trial, subject, behaviour type...) are the same.
I am relatively new to working in sql and have so far mostly just used it for extracting data. Is this something that is possible? If so how do I go about it?
Thanks :)
Edit - The data would be something like this
Condition Trial Group Subject Behaviour Duration **TotalDuration**
np 1 XX GBF132 interact 00:00:42
np 1 XX GBF132 interact 00:00:17
yp 1 ZZ HJR543 interact 00:01:03
yp 1 ZZ HJR543 interact 00:00:26
So there could be multiple interactions within a trial by the same individual and I would like to determine the overall interaction duration per trial.
But I have multiple subjects/behaviours/Groups per trial and condition so need a way to easily calculate the total duration of each behaviour when the condition, trial, group, subject, behaviour are the same .
I hope this makes it clearer!
AFAIK in recent MySQL versions they've added support for window functions. It seems that those functions can be used to solve your problem. I didn't test it, but it would be used somewhat like that:
SELECT
`condition`, `trial`, `group`, `subject`, `behaviour`,
`duration`,
SEC_TO_TIME(SUM(TIME_TO_SEC(`duration`))) OVER (PARTITION BY condition`, `trial`, `group`, `subject`, `behaviour`) AS timeSum
FROM `tests`;
Anyway, for older versions of MySQL the following might work for you:
SELECT
`condition`,
`trial`,
`group`,
`subject`,
`behaviour`,
`duration`, SEC_TO_TIME(SUM(TIME_TO_SEC(`duration`)))
FROM `tests`
GROUP BY `condition`, `trial`,`group`, `subject`,`behaviour`;
but that way you would kind of lose the "details". To replicate the way window functions work you would need to use something like:
SELECT `t1`.`condition`, `t1`.`trial`,`t1`.`group`, `t1`.`subject`,`t1`.`behaviour`, `t2`.`duration`,`t1`.`totalTime` FROM (SELECT
`condition`,
`trial`,
`group`,
`subject`,
`behaviour`,
`duration`, SEC_TO_TIME(SUM(TIME_TO_SEC(`duration`))) AS totalTime
FROM `tests` AS subt1
GROUP BY `condition`, `trial`,`group`, `subject`,`behaviour`) AS t1
JOIN `tests` AS t2 USING (`condition`, `trial`,`group`, `subject`,`behaviour`);
Here's the code snippet I've played around: http://sqlfiddle.com/#!9/e002f2/12/0
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.