需要子查询帮助

时间:2009-01-22 15:58:58

标签: sql subquery

我需要得到2个总和的数字,但我有问题,因为一个将是总订单,一个是订单不完整。这些使用相同的初始查询,但不完整的订单有一个额外的where子句。可以将这些放入查询中,以便我只获得2列。我以前做过内部查询,但我从来没有做过2个不同的where子句?!任何想法都很适合

使用总订单查询即时:

SELECT  Count(TBL_PROPERTY.PROPREF) AS TotalOrders

FROM    TBL_PROPERTY INNER JOIN 
        TBL_REPAIR_ORDER ON TBL_PROPERTY.PROPREF = TBL_REPAIR_ORDER.PROPREF INNER JOIN 
        TBL_REPAIR_VISIT ON TBL_REPAIR_ORDER.ORDERID = TBL_REPAIR_VISIT.ORDERID INNER JOIN
        tbl_contract ON tbl_repair_order.CONTRACT = tbl_contract.CONTRACT

WHERE   (TBL_CONTRACT.CONTRACT IN ('STE')) AND
        (TBL_REPAIR_ORDER.RAISEDDATE  BETWEEN '01/12/2008' AND DATEADD(hh,23,'01/01/2009'))

使用订单不完整查询:

SELECT  Count(TBL_PROPERTY.PROPREF) AS TotalOrders

FROM    TBL_PROPERTY INNER JOIN 
        TBL_REPAIR_ORDER ON TBL_PROPERTY.PROPREF = TBL_REPAIR_ORDER.PROPREF INNER JOIN 
        TBL_REPAIR_VISIT ON TBL_REPAIR_ORDER.ORDERID = TBL_REPAIR_VISIT.ORDERID INNER JOIN
        tbl_contract ON tbl_repair_order.CONTRACT = tbl_contract.CONTRACT

WHERE   (TBL_CONTRACT.CONTRACT IN ('STE')) AND
        (TBL_REPAIR_ORDER.RAISEDDATE  BETWEEN '01/12/2008' AND DATEADD(hh,23,'01/01/2009')) AND
 TBL_REPAIR_ORDER.STATUS <> 'Completed')

2 个答案:

答案 0 :(得分:1)

SELECT  Count(TBL_PROPERTY.PROPREF) AS TotalOrders
      , SUM( CASE WHEN TBL_REPAIR_ORDER.STATUS <> 'Completed' THEN 1 ELSE 0 END ) AS TotalNotCompleted

删除TBL_REPAIR_ORDER.STATUS&lt;&gt;从WHERE子句中“完成”。

答案 1 :(得分:-2)

使用您在主查询中作为表/列的两个查询。