这是像你一样准备桌子。
SET NOCOUNT ON
IF OBJECT_ID('tempdb..#result') IS NOT NULL
DROP TABLE #result
CREATE TABLE #result
(
resultname sysname NOT NULL
,ActivityDate DATE NOT NULL
,id INT NOT NULL
)
IF OBJECT_ID('tempdb..#resultdetail') IS NOT NULL
DROP TABLE #resultdetail
CREATE TABLE #resultdetail
(
resultname sysname NOT NULL
,ActivityDateType sysname NOT NULL
)
INSERT INTO #result( resultname, ActivityDate, id )
SELECT 'Result1','11/14/2013',1
UNION ALL SELECT 'Result1','11/14/2013',2
UNION ALL SELECT 'Result2','11/14/2013',3
UNION ALL SELECT 'Result3','11/14/2013',4
INSERT INTO #resultdetail( resultname, ActivityDateType )
SELECT 'Result1','DateType1'
UNION ALL SELECT 'Result2','DateType1'
UNION ALL SELECT 'Result3','DateType2'
SET NOCOUNT OFF
正如您所解释的,这是返回数据的最终查询。
请注意,我选择返回“Result1”和“Result3”的结果
SET NOCOUNT ON
IF OBJECT_ID('tempdb..#DynamicColumn_Select') IS NOT NULL
DROP TABLE #DynamicColumn_Select
CREATE TABLE #DynamicColumn_Select
(
ColumnName sysname NOT NULL PRIMARY KEY
)
/*Prepare the user input for which ResultName we need to generate Final Results*/
INSERT INTO #DynamicColumn_Select( ColumnName )
SELECT 'Result1' UNION ALL SELECT 'Result3'
DECLARE @CsvDynamicColumn_Select NVARCHAR(MAX)=''
,@CsvDynamicColumn_PvtIn NVARCHAR(MAX)=''
,@SQL NVARCHAR(MAX)=''
/*Prepare the Dynamic PIVOT IN Column List as CSV*/
SELECT @CsvDynamicColumn_PvtIn =
CASE WHEN @CsvDynamicColumn_PvtIn = ''
THEN ''
ELSE @CsvDynamicColumn_PvtIn + ','
END
+ N'['+ActivityDateType+N']'
FROM
(
Select DISTINCT t1.ActivityDateType
FROM #resultdetail t1
WHERE resultname IN
(SELECT ColumnName FROM #DynamicColumn_Select)
)qry
/*Prepare the Dynamic Select Column list as CSV*/
SELECT @CsvDynamicColumn_Select =
CASE WHEN @CsvDynamicColumn_Select = ''
THEN ''
ELSE @CsvDynamicColumn_Select + ','
END
+ ActivityDateType
FROM
(
Select DISTINCT t1.ActivityDateType
FROM #resultdetail t1
WHERE resultname IN
(SELECT ColumnName FROM #DynamicColumn_Select)
)qry
PRINT @CsvDynamicColumn_PvtIn
PRINT @CsvDynamicColumn_Select
SET @SQL = N'
SELECT resultname,id, '+ @CsvDynamicColumn_Select
+N'
FROM
(
SELECT resultname,id, '+@CsvDynamicColumn_Select
+N'
FROM
(
SELECT t1.resultname,t2.ActivityDateType,t1.ActivityDate,t1.id
FROM #result t1
JOIN #resultdetail t2
ON t1.resultname=t2.resultname
Where t1.resultname in (Select ColumnName From #DynamicColumn_Select)
)q1
PIVOT
(MAX(ActivityDate) FOR ActivityDateType IN ('+@CsvDynamicColumn_PvtIn+N'))pvt
)qry
'
PRINT @SQL
EXECUTE sp_executesql @SQL
SET NOCOUNT OFF
这是上述查询的结果