user3090731
user3090731

Reputation:

Select statement by group by total

I have two tables Contact and Invoice linked by ContactId

Please see fiddle

I am selecting all the contact who have spend more than 2500 per any year and the query works fine.

I wanted it to display in a below format. enter image description here

Any help on this please using sql-server. I can easily do this using crystal-report cross tab, but trying to do thing only using sql-server

Upvotes: 5

Views: 63

Answers (1)

GarethD
GarethD

Reputation: 69769

You can PIVOT, then UNPIVOT your data from your original query to get it in the desired format:

WITH T AS
(   SELECT  c.ContactID, 
            ContactName = c.Name,
            Year = DATEPART(YEAR, i.InvDate),
            Invoices = CAST(COUNT(i.InvoiceID) AS FLOAT),
            InvTotal = CAST(SUM(i.InvTotal) AS FLOAT)
    FROM    Invoice AS i
            INNER JOIN dbo.Contact AS c
                ON c.ContactID = i.InvContactID
    GROUP BY c.ContactID, c.Name, DATEPART(YEAR, i.InvDate)
    HAVING SUM(i.InvTotal) > 2000
)
SELECT  ContactName = CASE WHEN pvt.Measure = 'InvTotal' THEN '' ELSE pvt.ContactName END,
        pvt.Measure,
        [2012] = ISNULL(pvt.[2012], 0),
        [2013] = ISNULL(pvt.[2013], 0),
        [2014] = ISNULL(pvt.[2014], 0)
FROM    T
        UNPIVOT 
        (   Value
            FOR Measure IN ([Invoices], [InvTotal])
        ) AS upvt
        PIVOT
        (   SUM(Value)
            FOR [Year] IN ([2012], [2013], [2014])
        ) AS pvt
ORDER BY pvt.ContactName, Measure;

Example on SQL Fiddle

Upvotes: 3

Related Questions