合并3个Firebird查询

时间:2017-04-06 17:41:08

标签: sql firebird

我为我的Firebird数据库创建了3个查询。

1 - 按日期获取所有家庭

select 
     distinct oh.FAMILY
from 
     TRACKCODE_SUMMARY ts, 
     ORDER_HEAD oh 
where 
     oh.AMF_NUM = ts.AMF_NUM 
     and ts.DATE_INDUCTION >= '2017-04-06';

2 - 获取按日期和家庭生成的计数

select 
     count(*) AS Produced 
from 
     trackcode_summary ts, 
     order_head oh 
where 
     ts.AMF_NUM = oh.AMF_NUM 
     and ts.date_induction >= '2017-04-06'
     and oh.FAMILY like 'TULIP15BROAD';

3 - 按日期和家庭计算失败次数

select 
    count(*) AS Failed 
from 
    trackcode_summary ts, 
    order_head oh 
where 
    ts.AMF_NUM = oh.AMF_NUM 
    and ts.date_induction >= '2017-04-06' 
    and (ts.emr >= 1 or ts.current_status = 200) 
    and oh.FAMILY like 'TULIP15BROAD';

这三个查询完美分离。我需要合并到一个查询中。

我怎么能这样做?

1 个答案:

答案 0 :(得分:3)

怎么样

SELECT 
     oh.FAMILY

     ,
     SUM
     (
        CASE WHEN oh.FAMILY LIKE 'TULIP15BROAD' THEN 1 ELSE 0 END
     ) AS Produced  

     ,
     SUM
     (
        CASE WHEN (ts.emr >= 1 OR ts.current_status = 200) AND oh.FAMILY LIKE 'TULIP15BROAD' THEN 1 ELSE 0 END
     ) AS Failed  

FROM  
     TRACKCODE_SUMMARY ts, 
     ORDER_HEAD oh 
WHERE  
     oh.AMF_NUM = ts.AMF_NUM 
     AND ts.DATE_INDUCTION >= '2017-04-06';

GROUP BY oh.FAMILY 

BTW,而不是LIKE 'TULIP15BROAD',您应该使用= 'TULIP15BROAD'

此外,我认为您最好使用JOIN关键字以获得更好的清晰度。

FROM TRACKCODE_SUMMARY AS ts

INNER JOIN ORDER_HEAD AS oh 
    ON oh.AMF_NUM = ts.AMF_NUM
    AND ts.DATE_INDUCTION >= '2017-04-06'