• A classic CROSSTAB makes short work of this as a single "pivot" table. Please see the following article on what a CROSSTAB IS and how it works.

    http://www.sqlservercentral.com/articles/T-SQL/63681/

    SELECT Month = SUBSTRING(CONVERT(CHAR(30),DATEADD(mm,DATEDIFF(mm,0,RemediationDate),0),113),4,8)

    ,[RecycleCount] = SUM(CASE WHEN D_Type = 'Recycle' THEN 1 ELSE 0 END)

    ,[ReuseCount] = SUM(CASE WHEN D_Type = 'Reuse' THEN 1 ELSE 0 END)

    ,[RemarketCount] = SUM(CASE WHEN D_Type = 'Remarket' THEN 1 ELSE 0 END)

    ,[PassCount] = SUM(CASE WHEN Status = 'Pass' THEN 1 ELSE 0 END)

    ,[FailCount] = SUM(CASE WHEN Status = 'Fail' THEN 1 ELSE 0 END)

    ,[TotalLineItems] = COUNT(*)

    ,[TotalInvoices] = COUNT(DISTINCT Invoice)

    ,[AvgLineItemsPerInvoice] = (COUNT(*)+0.0)/COUNT(DISTINCT Invoice)

    FROM dbo.Remediation

    GROUP BY DATEDIFF(mm,0,RemediationDate)

    ORDER BY DATEDIFF(mm,0,RemediationDate)

    ;

    Here's the output using your test data...

    Month RecycleCount ReuseCount RemarketCount PassCount FailCount TotalLineItems TotalInvoices AvgLineItemsPerInvoice

    -------- ------------ ----------- ------------- ----------- ----------- -------------- ------------- ---------------------------------------

    Jan 2014 3 5 4 7 5 12 2 6.000000000000

    Feb 2014 4 1 1 4 2 6 2 3.000000000000

    (2 row(s) affected)

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)