Are there any ways to achieve dynamic pivoting tables in SQL Server through an elegant function? Pivoting tables is a basic utility which theoretically might be done in one line of code. All we need is to define parameters: column variable to pivot (change its values into column names), variable to aggregate, aggregate function, and table on which we perform the pivoting.
I look for alternatives to the syntax Microsoft proposes for pivoting tables in SQL Server in the 2019 year.
A practical alternative I found here: https://stackoverflow.com/a/45065584/1903793
All complex code is wrapped with a stored procedure. In this elegant one-liner, we define all parameters which are needed for pivoting.
exec [dbo].[USP_DYNAMIC_PIVOT] 'date','category','amount','dbo.temp','sum'
But the caveat of that solution is that it is a stored procedure so it requires a static table as input and it outputs also a static table. Would be better if it might be a sort of TVF from which we can select.
Update after comments. Until I started using SQL Server I did not even know that pivoting might be static. The need is to do dynamic pivoting. Lots of other applications do pivoting tables on the fly (Excel, Power BI, R) without constraint that column names must be known apriori. It might be a problem in 2005 to realize that pivoting might be done as a function with parameters. But, hey, we are going to the future, and it is ridiculous that we are heading next decades with the complex constrained syntax for this basic table transformation utility.