我有Contact
Invoice
和ContactId
请参阅fiddle
我选择的是每年花费超过2500的所有联系人,查询工作正常。
我希望它以下面的格式显示。
请使用sql-server
获取相关帮助。我可以使用crystal-report cross tab轻松完成此操作,但尝试仅使用sql-server
答案 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 强>