按组总计选择语句

时间:2014-06-23 08:58:29

标签: sql sql-server-2008-r2 pivot

我有Contact

链接的两个表InvoiceContactId

请参阅fiddle

我选择的是每年花费超过2500的所有联系人,查询工作正常。

我希望它以下面的格式显示。 enter image description here

请使用sql-server获取相关帮助。我可以使用crystal-report cross tab轻松完成此操作,但尝试仅使用sql-server

进行操作

1 个答案:

答案 0 :(得分:3)

您可以PIVOT,然后UNPIVOT原始查询中的数据,以获得所需的格式:

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