答案 0 :(得分:0)
你可以使用它。
DECLARE @columns NVARCHAR(MAX), @sql NVARCHAR(MAX);
SET @columns = N'';
SELECT @columns += N', ' + QUOTENAME(Process)
FROM
(
SELECT DISTINCT Process FROM SAMPLE_TABLE
) AS x;
SET @sql = N'SELECT [Date],'
+ STUFF(@columns, 1, 2, '')
+ 'FROM
(
SELECT [Date], Qty,Process FROM SAMPLE_TABLE
) AS j PIVOT
(
SUM(Qty) FOR Process IN ('
+ STUFF(REPLACE(@columns, ', [', ',['), 1, 1, '')
+ ')
) AS p ORDER BY p.[Date];';
EXEC sp_executesql @sql;
答案 1 :(得分:0)
如果它始终是这4个选项,请不要使用枢轴...使用条件聚合
select Date,
sum(case when Process = 'DESIGN' then Qty else 0 end) as DESIGN,
sum(case when Process = 'CODING' then Qty else 0 end) as CODING,
sum(case when Process = 'TESTING' then Qty else 0 end) as TESTING,
sum(case when Process = 'DATABASE' then Qty else 0 end) as [DATABASE]
from MyTable
group by Date
答案 2 :(得分:0)
我们可以使用Dynamic sql
获得所需的结果IF OBJECT_ID('Tempdb..#Temp') IS NOt NUll
Drop Table #Temp
;With cte (Developer, Process ,Qty, Date)
AS
(
SELECT 'XYZ','Design', 10 ,'26/06/2017' Union all
SELECT 'XYZ','Codein', 20 ,'26/06/2017' Union all
SELECT 'XYZ','Testin', 30 ,'26/06/2017' Union all
SELECT 'XYZ','Databa', 40 ,'26/06/2017' Union all
SELECT 'ABC','Design', 10 ,'26/06/2017' Union all
SELECT 'ABC','Codein', 20 ,'26/06/2017' Union all
SELECT 'ABC','Testin', 30 ,'26/06/2017' Union all
SELECT 'ABC','Databa', 40 ,'27/06/2017' Union all
SELECT 'XYZ','Design', 50 ,'27/06/2017' Union all
SELECT 'XYZ','Codein', 60 ,'27/06/2017' Union all
SELECT 'XYZ','Testin', 70 ,'27/06/2017' Union all
SELECT 'XYZ','Databa', 80 ,'27/06/2017' Union all
SELECT 'ABC','Design', 50 ,'27/06/2017' Union all
SELECT 'ABC','Codein', 60 ,'27/06/2017' Union all
SELECT 'ABC','Testin', 70 ,'27/06/2017' Union all
SELECT 'ABC','Databa', 80 ,'27/06/2017'
)
SELECT * INTO #Temp FROM cte
--Above i have created sample data for getting result
DECLARE @dynamicCol nvarchar(max),
@Sql nvarchar(max),
@dynamicCol2 nvarchar(max),
@dynamicCol3 nvarchar(max)
SELECT @dynamicCol=STUFF((SELECT DISTINCT ', ' + 'ISNULL('+Process +',''0'') AS '+ Process FROM #Temp
FOR XML PATH('')),1,1,'')
SELECT @dynamicCol2=STUFF((SELECT DISTINCT ', ' + Process FROM #Temp
FOR XML PATH('')),1,1,'')
SELECT @dynamicCol3=STUFF((SELECT DISTINCT ', ' + 'SUM( '+Process +' ) OVER( Partition by [Date] ) AS '+ Process FROM #Temp
FOR XML PATH('')),1,1,'')
SET @Sql='SELECT DISTINCT [Date],'+@dynamicCol3+' FROM
(
SELECT [Date] , '+ @dynamicCol +' From
(
SELECT * From
#temp
)AS Src
PIVOT
(
MAX([Qty]) For [Process ] IN ('+@dynamicCol2+')
)
AS Pvt
)DT
'
PRINT @Sql
EXEC(@Sql)
答案 3 :(得分:0)
如果您不希望提及特定的数据透视图和结果视图,但想要使用数据而不是
select Date1,cast(Process as varchar(200)) Status,sum(Qty) as Count from #temp group by Date1,Process