sql-two-worker一次性过滤

hgqdbh6s  于 2021-06-15  发布在  Mysql
关注(0)|答案(2)|浏览(247)

你好,stackoverflow的大师们。我需要帮助。
情况是:需要过滤掉工人,把他们工作的时间加起来。
数据库:

worker1    worker2    time_spent_in_seconds
X                     60
X          Y          60
Z          X          60

条件:如果worker1和worker2一起工作,他们的时间除以2,我希望得到:

X=120
Y=30
Z=30

谢谢您!

e3bfsja2

e3bfsja21#

您可以使用union all来尝试下面的方法

select worker,sum(val) from 
    (   select worker1 as worker , case when worker2 is not null
     then  time_spent/2 else time_spent end as val from test
    union all
    select worker2 , case when worker2 is not null
     then  time_spent/2 else time_spent end as val from test
    ) t where worker is not null
    group by worker

worker  sum(val)
X       120
Y       30
Z       30

演示链接

34gzjxbg

34gzjxbg2#

您需要为此使用开关功能

SELECT worker1, worker2, 
CASE WHEN worker2 is not null
     THEN (time_spent / 2)
     ELSE time_spent  END as time_spent
FROM test;

https://www.db-fiddle.com/f/h3khbuvsqckegxrhevpstt/0

相关问题