我想透视我的数据,但我可以有一个聚合函数:(
SELECT [IdTask] ,[Name] ,[LogType] ,[Fr] ,[Input] ,[CreatedAt] FROM [dbo].[vRapport]
我想有这样一个结果:
有人有办法这样做吗?谢谢尝试使用Pivot,但没有sum()count()就不起作用
kxe2p93d1#
您可以使用ROW_NUMBER()来取得1到10的数字清单。然后,您可以将MIN()或MAX()用于nvarchar列。
ROW_NUMBER()
MIN()
MAX()
nvarchar
SELECT [IdTask] , [Name] , [1] , [2] , [3] , [4] , [5] , [6] , [7] , [8] , [9] , [10] FROM ( SELECT [IdTask] , ROW_NUMBER() OVER (PARTITION BY [Name] ORDER BY [CreatedAt]) AS RowNum , [Name] , [Fr] FROM [dbo].[vRapport] ) AS SourceTable PIVOT ( MIN(Fr) FOR RowNum IN ([1], [2], [3], [4], [5], [6], [7], [8], [9], [10]) ) AS PivotTable;
如果您希望从您提供的查询开始,您可以使用CTE:
WITH CTE AS ( SELECT [IdTask] ,[Name] ,[LogType] ,[Fr] ,[Input] ,[CreatedAt] FROM [dbo].[vRapport] ) SELECT [IdTask] , [Name] , [1] , [2] , [3] , [4] , [5] , [6] , [7] , [8] , [9] , [10] FROM ( SELECT [IdTask] , ROW_NUMBER() OVER (PARTITION BY [Name] ORDER BY [CreatedAt]) AS RowNum , [Name] , [Fr] FROM CTE ) AS SourceTable PIVOT ( MIN(Fr) FOR RowNum IN ([1], [2], [3], [4], [5], [6], [7], [8], [9], [10]) ) AS PivotTable;
有关ROW_NUMBER()的更多信息,请访问:https://learn.microsoft.com/en-us/sql/t-sql/functions/row-number-transact-sql?view=sql-server-ver16
1条答案
按热度按时间kxe2p93d1#
您可以使用
ROW_NUMBER()
来取得1到10的数字清单。然后,您可以将
MIN()
或MAX()
用于nvarchar
列。如果您希望从您提供的查询开始,您可以使用CTE:
有关
ROW_NUMBER()
的更多信息,请访问:https://learn.microsoft.com/en-us/sql/t-sql/functions/row-number-transact-sql?view=sql-server-ver16