在一个选择中返回两个Count(*)结果

时间:2011-01-31 21:02:23

标签: sql select 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)`

3 个答案:

答案 0 :(得分: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 COUNT。

SELECT @totalItems AS totalItems, @failedItems AS failedItems

SELECT语句允许独立而没有FROM子句。

答案 1 :(得分:2)

难道你不能简单地在proc结束时选择那些变量吗?

SELECT @totalitems AS TotalItems, @faileditems AS FailedItems

答案 2 :(得分:0)

您正在寻找的是GROUP BY和HAVING