使用Rollup和子查询

时间:2016-06-23 09:43:33

标签: mysql

此查询针对同一个表(qcheck)运行多个计数,以便为我提供每个工程师分解为小时,天,周,月的测试总数。我还包括结果和数据的屏幕截图。

我想汇总所以我可以得到总数但不知道如何在使用子查询时这样做,因为我可以将总数加入任何东西

picture of data

Picture of results

代码:

expect(my_array).to any(include(id: 5))

1 个答案:

答案 0 :(得分:0)

由于连接条件xxxx.checkby =main.checkby,子查询中生成的汇总行将丢失。当任何一方为false时,此条件为null。特别是:null = nullfalse

此外,您可能会遇到一些边境情况,您将有一个星期超过两个月,因此一周的计数可能会超过当月的计数。这本身不是问题,但join链以每月计数开始的方式,您可能会错过每周计数中的一些记录。即,当前月份尚未记录的人的每周记录将不会计入周统计数据。

您获得的null值是外部(left)联接的结果。当外部连接条件为false时,righter连接表上的所有字段(也是计数)在引用时将产生null

所有上述问题都可以通过一个大的子查询来解决,使用更精细的case when条件而不是where条件:

select    *
from      (
          select   coalesce(checkby, 'Total') as checkby_or_total,
                   count(case when last_day(finishdate) = last_day(curdate())
                               and result = 'fully tested & working' 
                         then 1 end) as mfully,
                   count(case when last_day(finishdate) = last_day(curdate())
                               and result = 'faulty' 
                         then 1 end) as mfaulty,
                   count(case when last_day(finishdate) = last_day(curdate())
                         then 1 end) as mtotal,
                   count(case when date(finishdate) = curdate()
                               and result = 'fully tested & working' 
                         then 1 end) as dfully,
                   count(case when date(finishdate) = curdate()
                               and result = 'faulty'
                         then 1 end) as dfaulty,
                   count(case when date(finishdate) = curdate()
                         then 1 end) as dtotal,
                   count(case when yearweek(finishdate) = yearweek(curdate())
                               and result = 'fully tested & working' 
                         then 1 end) as wfully,
                   count(case when yearweek(finishdate) = yearweek(curdate())
                               and result = 'faulty'
                         then 1 end) as wfaulty,
                   count(case when yearweek(finishdate) = yearweek(curdate())
                         then 1 end) as wtotal,
                   count(case when finishdate >= now() - interval 1 hour
                               and result = 'fully tested & working' 
                         then 1 end) as lfully,
                   count(case when finishdate >= now() - interval 1 hour
                               and result = 'faulty'
                         then 1 end) as lfaulty,
                   count(case when finishdate >= now() - interval 1 hour
                         then 1 end) as ltotal
          from     qcheck
          where    checkby not in ('michael', 'chaz')
          group by checkby with rollup) as main
order by  checkby_or_total = 'Total',
          mtotal desc

我还介绍了一些不同的条件:

  • 使用last_day(finishdate) = last_day(curdate())
  • 可以更有效地制作月份条件
  • 当天的条件可能是date(finishdate) = curdate(),尽管这与您使用的条件不完全相同。但也许你想考虑这个。