Home > Database > Mysql Tutorial > How Can I Pivot a SQL Table Using CASE WHEN to Avoid Duplicate Rows?

How Can I Pivot a SQL Table Using CASE WHEN to Avoid Duplicate Rows?

Barbara Streisand
Release: 2025-01-11 15:47:43
Original
961 people have browsed it

How Can I Pivot a SQL Table Using CASE WHEN to Avoid Duplicate Rows?

Use the CASE WHEN statement in SQL to perform column pivoting

The pivot operation in SQL refers to converting vertically arranged columns in the data table into horizontally arranged columns. This is usually accomplished using the CASE WHEN statement.

Suppose there is a table with three columns: name, value and amount. The goal is to transform the data into a new representation: each row represents a name and each column represents a specific value in the val column, such as 'Val1' and 'Val2'.

You have tried writing an initial query using a CASE WHEN statement, but the results are not quite correct. Specifically, the rows for John and Peter are repeated twice, with one row containing the amount value associated with val = 1 and the other row containing the amount value associated with val = 2.

To solve this problem, we can use the SUM() aggregate function in conjunction with the CASE WHEN statement. By summing the amounts associated with each val value, we effectively group the rows for each name and merge the values ​​into a single column.

The following modified query will produce the desired results:

<code class="language-sql">SELECT 
  name,
  SUM(CASE WHEN val = 1 THEN amount ELSE 0 END) AS amountVal1,
  SUM(CASE WHEN val = 2 THEN amount ELSE 0 END) AS amountVal2
FROM bank GROUP BY name</code>
Copy after login

This query sums the amount of each val value in each name group and gets the following output:

name amountVal1 amountVal2
John 2000 1888
Peter 1999 1854

The above is the detailed content of How Can I Pivot a SQL Table Using CASE WHEN to Avoid Duplicate Rows?. 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