我有3个表:(简化此问题)
REQUIREMENTS
:ID(PK),RequirementDescription CUSTOMERS
:ID(PK),客户名称CUSTOMER_REQUIREMENTS
(连接表):ID(PK),RequirementID(FK到REQUIREMENTS表),CustomerID(FK到CUSTOMERS表),DateCompleted 问题:我需要在asp.net中创建一个gridview,它基本上显示左侧的需求,所有客户作为列标题,DateCompleted
作为“交集”。我怎么能这样做?
例如:
答案 0 :(得分:1)
尝试使用以下sql并将临时表替换为您的表:
创建表#REQUIREMENTS ( ID INT, RequirementDescription VARCHAR(100) )
创建表#CUSTOMERS ( ID INT, 客户名称VARCHAR(100) )
创建表#CUSTOMER_REQUIREMENTS ( ID INT, RequirementID INT, CustomerID INT, DateCompleted DATE )
插入#REQUIREMENTS VALUES(1,'要求1')
插入#REQUIREMENTS VALUES(2,'要求2')
插入#REQUIREMENTS VALUES(3,'要求3')
插入#REQUIREMENTS VALUES(4,'要求4')
插入#CUSTOMERS VALUES(1,' JOHN')
插入#CUSTOMERS VALUES(2,' MARY')
插入#CUSTOMERS VALUES(3,' BOB')
插入#CUSTOMER_REQUIREMENTS VALUES(1,1,1,' 2-2-2014')
插入#CUSTOMER_REQUIREMENTS VALUES(1,2,1,' 2-2-2014')
插入#CUSTOMER_REQUIREMENTS VALUES(1,1,2,' 2-2-2014')
插入#CUSTOMER_REQUIREMENTS VALUES(1,2,2,' 2-2-2014')
插入#CUSTOMER_REQUIREMENTS VALUES(1,3,2,' 2-2-2014')
插入#CUSTOMER_REQUIREMENTS VALUES(1,4,2,' 2-2-2014')
DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE @ColumnName AS NVARCHAR(MAX)
SELECT @ ColumnName = ISNULL(@ColumnName +',','')+ QUOTENAME(CustomerName)FROM(SELECT DISTINCT CustomerName FROM #CUSTOMERS)AS Courses
SET @DynamicPivotQuery = N' SELECT ReqID,ReqDes,' + @ColumnName +' 从 ( 选择 TEMP.ReqID, TEMP.ReqDes, TEMP.CusName, CusReq.DateCompleted 从 ( 选择 req.ID为ReqID, req.RequirementDescription为ReqDes, cus.ID为CusID, cus.CustomerName为CusName 从 #REQUIREMENTS req,#CUSTOMERS cus )AS TEMP LEFT JOIN #CUSTOMER_REQUIREMENTS为CusReq 上 TEMP.ReqID = CusReq.RequirementID AND Temp.CusID = CusReq.CustomerID )AS TEMP1 PIVOT(MAX(TEMP1.DateCompleted) FOR CusName IN(' + @ColumnName +'))AS PVTTable'
EXEC sp_executesql @DynamicPivotQuery
DROP TABLE #CUSTOMER_REQUIREMENTS
DROP TABLE #CUSTOMERS
DROP TABLE #REQUIREMENTS