1

I want to have a SELECT statement name columns based on other column values.

Let's say I have a table with column names like q_1, q_2 and other columns like q_1_name and q_2_name

Right now we are doing something like

SELECT SUM(q_1), SUM(q_2) from mytable;

I'd like to get a result set with the columns named for the values in q_1_name and q_2_name

SELECT SUM(q_1) as (q_1_name), SUM(q_2) as (q_2_name) from mytable;

Any chance you know a way to do this?

Strawberry
  • 33,750
  • 13
  • 40
  • 57
Pól
  • 140
  • 11
  • 1
    A query cannot have "dynamic" column names. Just think about (1) for your query you are summing multiple records, which record would you expect the value to be pulled from, (2) in a non-aggregating query with numerous result rows, which row's _name value should be used? – Uueerdo May 09 '18 at 18:49
  • 2
    If you need to create dynamic SQL, you have to do it in a stored procedure with `PREPARE` and `EXECUTE`. – Barmar May 09 '18 at 19:27
  • Can you provide an example of source data and the resultset you wish to get? Also, please specify what task you're trying to accomplish. It looks like you've chosen the wrong approach. – G. Kashtanov May 09 '18 at 19:38

1 Answers1

0

You can use a simply alias AS

SELECT SUM(q_1) as q_1_name, SUM(q_2) as q_2_name from mytable;

or using a subselect

select t.q_1_name, t.q_2_name
from (
SELECT SUM(q_1) as q_1_name, SUM(q_2) as q_2_name from mytable
) t;
ScaisEdge
  • 131,976
  • 10
  • 91
  • 107
  • I don't want the columns literally named *q_1_name* I wanted them named for the contents of that column. – Pól May 10 '18 at 22:41
  • 1
    You mean that q_1_name is a var ? ... if so you must do using dinamic sql server side – ScaisEdge May 11 '18 at 07:57