2011-01-31 27 views
3

我有一个存储过程,我希望它返回以下...返回两个COUNT(*)的结果中选择一个

TotalItems | FailedItems 
@totalItems | @failedItems 

where --> @totalItems = `SELECT COUNT(*) 
    From dbo.OdsBuild AS P 
    where P.StartTime Between @StartDate and @EndDate 
    AND P.Official = 1` 

where --> @failedItems = `SELECT COUNT(*) 
    From dbo.Items AS P 
    where p.StartTime Between @StartDate and @EndDate 
    AND P.Official = 1 AND (P.Result = 7 OR P.Result = 8 OR P.Result = 14)` 

回答

4

子查询SELECT COUNTs

SELECT 
    (SELECT COUNT(*) 
     From dbo.OdsBuild AS P 
     where P.StartTime Between @StartDate and @EndDate 
     AND P.Official = 1) totalItems , 
    (SELECT COUNT(*) 
     From dbo.Items AS P 
     where p.StartTime Between @StartDate and @EndDate 
     AND P.Official = 1 AND (P.Result = 7 OR P.Result = 8 OR P.Result = 14)) failedItems 

如果您已经将它们设置为变量,那么您不必重复SELECT COUNTs。

SELECT @totalItems AS totalItems, @failedItems AS failedItems 

SELECT语句允许在没有FROM子句的情况下独立运行。

0

你所寻找的是GROUP BY和HAVING

2

难道你不能简单地选择这些变量在你的过程结束?

SELECT @totalitems AS TotalItems, @faileditems AS FailedItems 
相关问题