For tips on how to write dynamic pivots you can see here: https://www.sommarskog.se/dynamic_sql.html#pivot Note that this link will bring you right into a longer article dynamic SQL. If you are not acquainted with dynamic SQL, you may be better off starting from the beginning of the article. This task requires dynamic SQL.
... as long as you insist on doing it in SQL Server. It may be better to return a relational result set and pivot client-side instead.