Home > Database > Mysql Tutorial > How to Transpose Rows into Columns in DB2?

How to Transpose Rows into Columns in DB2?

Mary-Kate Olsen
Release: 2024-12-30 15:39:18
Original
647 people have browsed it

How to Transpose Rows into Columns in DB2?

Transposing Rows into Columns in DB2

When working with data in a database, it may be necessary to transpose rows, meaning to flip the rows and columns. This can be useful for data analysis, reporting, and other purposes.

If you have a DB2 table with rows that you want to transpose into columns, there are several methods you can use. One approach is to use correlated subqueries, which can be efficient for small datasets.

SELECT 
  A.ItemID,
  MAX(CASE WHEN A.Item = 'Meeting'  THEN Value END) AS Meeting,
  MAX(CASE WHEN A.Item = 'Advise'   THEN Value END) AS Advise,
  MAX(CASE WHEN A.Item = 'NoAdvise' THEN Value END) AS NoAdvise
FROM A
GROUP BY A.ItemID
Copy after login

This query uses correlated subqueries to find the maximum value for each item in each row. The MAX() function is used to aggregate the values, and the CASE statement is used to determine which column to assign the value to.

Another method for transposing rows into columns is to use a combination of aggregation and pivot functions. This approach can be more efficient for large datasets, as it uses a single SQL statement to perform the transposition.

SELECT ItemID,
       MAX(CASE WHEN Item = 'Meeting'  THEN Value END) AS Meeting,
       MAX(CASE WHEN Item = 'Advise'   THEN Value END) AS Advise,
       MAX(CASE WHEN Item = 'NoAdvise' THEN Value END) AS NoAdvise
FROM (
    SELECT ItemID, Item, Value
    FROM TableName
) AS t
GROUP BY ItemID
PIVOT (MAX(Value) FOR Item IN ('Meeting', 'Advise', 'NoAdvise'))
Copy after login

This query uses the PIVOT() function to transpose the data. The PIVOT() function takes two arguments: the column to pivot on (in this case, Item), and the list of values to include in the new columns (in this case, Meeting, Advise, and NoAdvise).

The above is the detailed content of How to Transpose Rows into Columns in DB2?. 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