Home >Database >Mysql Tutorial >How Can I Pivot T-SQL Data Without Using Aggregation Functions?

How Can I Pivot T-SQL Data Without Using Aggregation Functions?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-20 10:01:08655browse

How Can I Pivot T-SQL Data Without Using Aggregation Functions?

T-SQL Data Pivoting: An Aggregation-Free Approach

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn