0

I have a table similar to the following -

id name subject score
1 XYZ English 50
1 XYZ Math 30

Now I need to something as follows-

id name English Math
1 XYZ 50 30

I tried UNION and JOIN but nothing worked.

Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228
ladsaylee
  • 27
  • 7

1 Answers1

1

After I fixed the example in the question to make sense, this would produce your desired result:

SELECT *
FROM   crosstab(
   'SELECT id, name, subject, score
    FROM   tbl
    ORDER  BY 1,3'  -- just "ORDER BY 1" works, too
  , $$VALUES ('Math'::text), ('English')$$
   ) AS ct (id int, name text, "Math" int, "English" int);

fiddle

Detailed explanation:

In particular, to add "extra" columns (name in this example):

Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228
  • What if I have multiple columns that needs to be separated? Example: with score column , I also have total column which needs to be divided based on subject. How can that be done? – ladsaylee Mar 20 '23 at 07:30
  • @ladsaylee: Please ask a new question with the necessary detail. – Erwin Brandstetter Mar 20 '23 at 12:43