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
Release: 2025-01-20 10:01:08
Original
632 people have browsed it

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template