Returning two counters (*) results in one selection

I have a stored procedure and I want it to return the following ...

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
source share
3 answers

Subquery 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

If you have already set them as variables, of course, you do not need to repeat SELECT COUNT.

SELECT @totalItems AS totalItems, @failedItems AS failedItems

SELECT statements allow autonomously without FROM clauses.

+4
source

Can't you just select these variables at the end of your process?

SELECT @totalitems AS TotalItems, @faileditems AS FailedItems
+2
source

What you are looking for is GROUP BY and HAVING

0
source

Source: https://habr.com/ru/post/1789086/


All Articles