您好我正在寻找一个SQL查询来根据客户的特定条件选择最大记录。目前的情况如下
Customer Activity Date
1 1 01/02/2015
1 1 02/02/2015
1 1 03/02/2015
1 2 05/02/2015
1 2 07/02/2015
1 3 06/02/2015
2 1 01/01/2015
2 2 05/01/2015
2 3 11/01/2015
My Required Resultset应该类似于
Customer Activity1Maxdate Activity2Maxdate Activity3MaxDate
1 03/02/2015 07/02/2015 06/02/2015
2 01/01/2015 05/01/2015 11/01/2015
此处的活动限于4或5,因此不需要动态制柱
任何帮助请 干杯
答案 0 :(得分:0)
你所问的是一个Pivot表 Sql server有一个用于pivot的关系运算符,你可以阅读它的文档here。
试试这个:
SELECT Customer,
[0] As Activity1Maxdate
, [1] As Activity2Maxdate
, [2] As Activity3Maxdate
, [3] As Activity4Maxdate
, [4] As Activity5Maxdate
FROM YourTable
PIVOT
(
MAX(Date)
FOR Activity IN ([0], [1], [2], [3], [4])
) AS PivotTable;