0

I am newbie in SQL so apologize if the question does not make sense.

I have a table that looks like (I am on google colab)

CREATE TEMP TABLE test (
    name STRING,
    subjectId INT,
    score INT
);

INSERT INTO test (name, subjectId, score) VALUES ('David', 123, 90);
INSERT INTO test (name, subjectId, score) VALUES ('David', 10, 80);
INSERT INTO test (name, subjectId, score) VALUES ('Ana', 34, 75);
INSERT INTO test (name, subjectId, score) VALUES ('Ryan', 123, 100);

enter image description here

There is a column called subjectId. I would like to apply the PIVOT operator on. I do not know what are the distinct values in this column. So I first create a string to record the distinct value of this column:

DECLARE subjects STRING;

SET subjects = ( 
  SELECT 
    CONCAT('(', STRING_AGG(DISTINCT CAST(subjectId AS STRING), ', '), ')'),
  FROM 
    test
);

Now I can proceed to apply the PIVOT operation:

EXECUTE IMMEDIATE format("""

  SELECT 
    *
  FROM (
    SELECT name, subjectId, score FROM test
      ) AS T
  PIVOT
  (
      max(score) for subjectId in %s
  ) AS P
""", subjects);

This give me the following table: enter image description here

Now you can see the columns are named according to the distinct values of the subjectId column. What I would like to do is to rename those columns to something like subject1, subject2, subject3, etc., and I do not care about the order. How can I do that?

jarlh
  • 42,561
  • 8
  • 45
  • 63
Ryan
  • 219
  • 2
  • 11
  • [Dynamic Pivot Tables in SQL Server](https://www.sqlshack.com/dynamic-pivot-tables-in-sql-server/) – Maciej Los Feb 25 '22 at 21:54
  • @MaciejLos I do not see where it says how to rename the columns – Ryan Feb 26 '22 at 01:36
  • AFAIK, you can't just alias pivot columns. You need to create another column that contains the header values "subject1", "subject2", etc... See here for example https://stackoverflow.com/questions/71239164/creating-a-distinct-list-of-names-with-dynamic-columns/71256003#71256003 – SOS Feb 27 '22 at 06:30
  • 1
    Also, SQL is a language and could refer to any dbms :-) Since syntax and capabilities vary greatly by vendor and version, please be sure to include which dbms you're using and which version # in the question tags. – SOS Feb 27 '22 at 06:37

0 Answers0