如何在不删除满足条件的所有条目的情况下限制选择?

时间:2011-12-07 20:11:45

标签: mysql sql join group-by

我们根据已完成的估算工作除以已支付的小时数计算奖金。我们系统中有一个人没有得到我们的报酬,我想将他从报告中删除。

在此查询中,我获得该用户的每个批次的所有跟踪时间除以该批次上跟踪的总时间,减去[名称]。

批处理包含的任务包含estimated_nonrecurring和estimated_recurring。 批次有batch_logs,其中包含time_elapsed,即批次实际处理的时间。

正在发生的事情不是选择所有批次,而是将所有跟踪该用户的时间与[名称]未跟踪的跟踪总时间进行比较,而忽略了每个批次[ name]作为其中的一个条目。

这是我对比率的选择声明。

SELECT user_time_by_batch.batch_id, userid, user_time_by_batch / total_time_by_batch as ratio FROM 
( 
SELECT SUM(time_elapsed) user_time_by_batch, userid, batch_id 
FROM batch_log 
inner join batches on batch_log.batch_id = batches.id 
Where start_time between (?) and (?) 
   and end_time is not null and time_elapsed BETWEEN \"00:00:00\" AND \"10:00:00\" 
   and batch_id not in (\"-1\", \"-2\", \"-3\", \"-4\", \"-5\", \"-6\", \"-7\", \"-8\", \"-9\", \"-10\", \"-11\", \"-12\", \"-13\", \"-14\", \"-15\", \"-16\", \"-17\") 
   and batches.operation_id = ? 
   and batch_log.userid = ? 
GROUP BY batch_id, userid 
)  user_time_by_batch 
INNER JOIN 
( 
SELECT SUM(time_elapsed) total_time_by_batch, batch_id 
FROM batch_log 
inner join batches on batch_log.batch_id = batches.id 
Where start_time between (?) and (?)  
  and end_time is not null and time_elapsed BETWEEN \"00:00:00\" AND \"10:00:00\" 
  and batch_id not in (\"-1\", \"-2\", \"-3\", \"-4\", \"-5\", \"-6\", \"-7\", \"-8\", \"-9\", \"-10\", \"-11\", \"-12\", \"-13\", \"-14\", \"-15\", \"-16\", \"-17\") 
  and batches.operation_id = ? 
  and batch_log.userid != 'name' 
GROUP BY batch_id 
) total_time_by_batch 
ON user_time_by_batch.batch_id = total_time_by_batch.batch_id ;

1 个答案:

答案 0 :(得分:1)

我要考虑的一件事是将batch_log.userid!='smacpherson'移入JOIN语句而不是WHERE子句。我不确定这是多么的最佳实践,但我通过这种方式成功地消除了奇怪的数据问题。

所以:

INNER JOIN 
( 
SELECT SUM(time_elapsed) total_time_by_batch, batch_id 
FROM batch_log 
inner join batches on batch_log.batch_id = batches.id and batch_log.userid != 'smacpherson'
Where start_time between (?) and (?)  
  and end_time is not null and time_elapsed BETWEEN \"00:00:00\" AND \"10:00:00\" 
  and batch_id not in (\"-1\", \"-2\", \"-3\", \"-4\", \"-5\", \"-6\", \"-7\", \"-8\", \"-9\", \"-10\", \"-11\", \"-12\", \"-13\", \"-14\", \"-15\", \"-16\", \"-17\") 
  and batches.operation_id = ?  
GROUP BY batch_id 
) total_time_by_batch