基于下表
id Title Date Metadata
------------------------------------
1 A 08/01/2010 M1
1 A 10/05/2010 M2
1 A 03/15/2011 M3
2 B 09/20/2010 M1
2 B 01/15/2011 M2
3 C 12/15/2010 M1
输入变量将是开始日期和结束日期。例如,
@startDate = '07/01/2010'
@endDate = '06/30/2011'
如何生成以下输出?
Title Jul-10 Aug-10 Sep-10 Oct-10 Nov-10 Dec-10 Jan-11 Feb-11 Mar-11 Apr-11 May-11 Jun-11
-------------------------------------------------------------------------------------------
A Null M1 Null M2 Null Null Null Null M3 Null Null Null
B Null M1 Null Null Null Null M2 Null Null Null Null Null
C Null Null Null Null Null M1 Null Null Null Null Null Null
答案 0 :(得分:3)
您所寻求的通常称为交叉表查询。如果你问的是如何在给出 static 列列表的情况下构建交叉表查询,你可以这样做:
Select Title
, Min( Case When DatePart(mm, [Date]) = 7 And DatePart(yy, [Date]) = 2010 Then MetaData End ) As [Jul-10]
, Min( Case When DatePart(mm, [Date]) = 8 And DatePart(yy, [Date]) = 2010 Then MetaData End ) As [Aug-10]
, Min( Case When DatePart(mm, [Date]) = 9 And DatePart(yy, [Date]) = 2010 Then MetaData End ) As [Sep-10]
...
From Table
Where [Date] Between @StartDate And @EndDate
Group By Title
同样,您可以使用Broken Link建议的PIVOT功能。但是,上述解决方案和PIVOT功能都依赖于静态列声明。如果你想要的是一个动态列列表(a.k.a.动态交叉表),那么你就超出了T-SQL主要设计的范围。它可能可能带有一些不稳定的动态SQL,但它很脆弱且很麻烦。相反,您应该在中间层组件中构建结果集,或者使用将构建交叉表结果的报告工具。
答案 1 :(得分:2)
使用Pivot表..
一个简单的例子..
USE AdventureWorks;
GO
SELECT DaysToManufacture, AVG(StandardCost) AS AverageCost
FROM Production.Product
GROUP BY DaysToManufacture;
DaysToManufacture AverageCost
0 5.0885
1 223.88
2 359.1082
4 949.4105
查询
SELECT 'AverageCost' AS Cost_Sorted_By_Production_Days,
[0], [1], [2], [3], [4]
FROM
(SELECT DaysToManufacture, StandardCost
FROM Production.Product) AS SourceTable
PIVOT
(
AVG(StandardCost)
FOR DaysToManufacture IN ([0], [1], [2], [3], [4])
) AS PivotTable;
结果
Cost_Sorted_By_Production_Days 0 1 2 3 4
AverageCost 5.0885 223.88 359.1082 NULL 949.4105