2016-07-19 49 views
0

我得到的一个单位进行的测试次数:如何用mysql中的空值替换丢失的记录?

select 
    date(START_DATE_TIME), product_id, BATCH_SERIAL_NUMBER, count(*) 
from 
    (select START_DATE_TIME, product_id, uut_serial_number, BATCH_SERIAL_NUMBER 
     from uut_result  
     where START_DATE_TIME >= '2016-07-01 00:00:00' 
     and START_DATE_TIME <= '2016-07-07 23:59:59') as passtbl 
     group by date(START_DATE_TIME), product_id, batch_serial_number; 

我取按天细分通过单位测试次数:

select 
    date(START_DATE_TIME), product_id, BATCH_SERIAL_NUMBER, count(*) 
from 
    (select START_DATE_TIME, product_id, uut_serial_number, BATCH_SERIAL_NUMBER 
     from uut_result  
     where START_DATE_TIME >= '2016-07-01 00:00:00' 
     and START_DATE_TIME <= '2016-07-07 23:59:59'  
     and uut_status = 'passed') as passtbl 
     group by date(START_DATE_TIME), product_id, batch_serial_number; 

什么,我发现是,有些单元根本没有任何通行记录,所以第二个查询返回的记录数比第一个少。这是打破后处理。有没有办法避免记录的缺失,并用空值或其他虚拟值替换它?

回答

1
select date(START_DATE_TIME), 
     product_id, 
     BATCH_SERIAL_NUMBER, 
     status, 
     count(*) 
from (select *, 
      case when uut_status = 'passed' then uut_status 
       else 'other statuses' 
       end status 
     from uut_result)  
where START_DATE_TIME >= '2016-07-01 00:00:00' 
and START_DATE_TIME <= '2016-07-07 23:59:59' 
group by date(START_DATE_TIME), 
     status, 
     product_id, 
     batch_serial_number; 
0

我的标准答案,一切都像这是你失去细节,使用公用表表达式和窗口功能,而不是使用组,不得不努力恢复它们。

为了得到一个虚拟的行你可以使用一个联盟这样的:

;with myCTE (unitId, otherdetail, passed) 
as (
    select unitDetail, otherdetail, Sum(1) Over (partition by unit) as passed 
    from sourceTable 
) 
SELECT unitid, otherDetail, passed 
from myCTE 
where startDate >= lowerbound and startdate < upperBound 

UNION 
SELECT unitId, otherdetail, 0 as passed 
from sourceTable S 
where not exists (select 1 from myCTE where myCTE.unitId = S.unitID 
     and startDate >= lowerbound and startdate < upperBound) 

我想这也是你所需要的一个相当不错的草图。 此外,我会用半开间隔来比较时间 关于startTime介于11:59:59和0:00之间的下一个机会,下一个 一天。

你从来没有提到过什么数据库引擎[杜,这是在标题我正在寻找一个标签]。 CTE在SQL Server和Oracle上可用,但不在MySQL上。

对于大多数用途,您可以替换相关的子查询,但必须重复自己。 ';'之前WITH是SQL 服务器的怪癖。

由于您是MySQL,因此您必须将CTE作为引用的子查询来复制。或者,也许你有表值函数?