I needed to figure out how to Pivot a set of data I had, and the code works as needed, but the issue is that I don't really understand why that is. Can anyone help out a rookie and explain exactly why the code below decided to 'SELECT @columns = COALESCE + ...

Why does he specifiy two arguments in the COALESCE function? Is it just to return all of the columns in that table? If so, can someone break down exactly how it does that. I'm pulling this code from this website as reference: ( http://www.tsqltutorials.com/pivot.php )

Thanks in advance!

DECLARE @columns VARCHAR(8000)

SELECT @columns = COALESCE(@columns + ',[' + cast(Variable as varchar) + ']',
'[' + cast(Variable as varchar)+ ']')
FROM #temp123
GROUP BY Variable


DECLARE @query VARCHAR(8000)

SET @query = '
SELECT *
FROM #temp123
PIVOT
(
MAX(VaribleValue)
FOR [Variable]
IN (' + @columns + ')
)
AS p'

EXECUTE(@query)
有帮助吗?

解决方案

From the structure of the code I can see that the query is designed for a dynamic PIVOT, which means that the number of columns can vary; unlike a traditional PIVOT in which you have to specify the exact columns to pivot for

The COALESCE keyword is similar to the ISNULL function, but the main differences is that you can specify multiple values to check for:

So for example you can use SELECT COALESCE(NULL, NULL, 1, NULL) AS [Output]; The value of [Output] will be 1. It is the same as saying, if the first value is NULL; return the next; if the second value is NULL; use the third; and so on until the first NON-NULL value is found.

So in your case, the COALESCE keyword will check the @columns variable appended to the Variable field; if it is NULL (which can occur if any value in the Variable field is NULL) then it will simply use the next statement.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top