Data transformation often requires unpivoting, typically achieved using aggregate functions. However, pivoting without aggregation is also possible.
Consider a table where each row represents a customer, including a CustomerID, DBColumnName, and the corresponding Data. The goal is to pivot this data, organizing each customer's data into separate columns based on their DBColumnName.
<code class="language-sql">SELECT CustomerID, MIN(CASE WHEN DBColumnName = 'FirstName' THEN Data END) AS FirstName, MIN(CASE WHEN DBColumnName = 'MiddleName' THEN Data END) AS MiddleName, MIN(CASE WHEN DBColumnName = 'LastName' THEN Data END) AS LastName, MIN(CASE WHEN DBColumnName = 'Date' THEN Data END) AS Date FROM table GROUP BY CustomerID;</code>
This T-SQL query uses conditional logic (CASE statements) to select data based on DBColumnName. The MIN()
function ensures only one value is selected for each customer's column. This effectively pivots the data without using aggregation in the traditional sense, organizing each customer's attributes into distinct columns. This method avoids the potential issues associated with aggregation when dealing with non-numeric data.
The above is the detailed content of How Can I Pivot T-SQL Data Without Using Aggregation Functions?. For more information, please follow other related articles on the PHP Chinese website!