pandas pivot_table SQL equivalent
Asked Answered
E

1

6

Can we in SQL (preferably Postgresql) mimic the pandas function pivot_table?

For example, let's say we have a table with the following 3 columns:

   Name        Day       Value
   John     Sunday           6
   John     Monday           3
   John     Tuesday          2
   Mary     Sunday           6
   Mary     Monday           4
   Mary     Tuesday          7
   Alex     Tuesday          1

I want to pivot the table so that the index is the name, the columns are the days, and cells are the values:

    names  Monday  Sunday  Tuesday
    John       3       6        2
    Mary       4       6        7
    Alex     null    null       1

Part of the example was taken from the question Transform a 3-column dataframe into a matrix

Euphonious answered 16/11, 2021 at 17:28 Comment(0)
U
0

To my knowledge there is nothing built in but you can use this:

SELECT 
    Name AS names,
    MAX(CASE WHEN Day = 'Monday' THEN Value END) AS Monday,
    MAX(CASE WHEN Day = 'Sunday' THEN Value END) AS Sunday,
    MAX(CASE WHEN Day = 'Tuesday' THEN Value END) AS Tuesday
FROM 
    names_table
GROUP BY 
    Name
ORDER BY 
    Name;
Ummersen answered 11/10, 2024 at 18:13 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.