AdamLazaruso
AdamLazaruso

Reputation: 572

Using data from table as column heading

I have a database with two tables, component_psar and tbl_info. The component_psar table has the field 'tbl_id' which references the corresponding 'id' field in tbl_info.

I need to write a query in which data is taken from tbl_info and used as the heading for that column in component_psar.

So if the component_psar table contained the data:

tbl_id | col_1
1      |  Hello
1      |  Hi
1      |  What's up?

And then the tbl_info table:

id | heading
1  | Greetings

I would like it to display as:

Greetings
Hello
Hi
What's up?

I've written the following SQL query to try and accomplish this:

SELECT component_psar.col_1 as (SELECT tbl_info.heading FROM tbl_info, component_psar WHERE tbl_info.id = '1') FROM tbl_info, component_psar WHERE (component_psar.tbl_id = '1')

But this just throws a syntax error:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(SELECT tbl_info.heading FROM tbl_info, component_psar WHERE tbl_info.id = compo' at line 1

Can anyone offer any suggestions as to how I might accomplish this? Looking at other questions has led me to reading into pivot tables but I haven't seen any way in which this might work for my purposes. Perhaps I'm misunderstanding it.

Any help with this would be much appreciated.

Upvotes: 1

Views: 222

Answers (2)

David Turvey
David Turvey

Reputation: 2941

I would try to separate out the process of retrieving data from the database and formatting it for display.

A simple inner join should work for your query

select tbl_info.heading as Heading,component_psar.col_1 as Value 
from tbl_info 
inner join component_psar on component_psar.tbl_id = tbl_info.id
order by tbl_info.heading

this will give you the following query results

Heading   | Value 
----------+--------------
Greetings |  Hello
Greetings |  Hi
Greetings |  What's up?

How you process this for display depends your programming environment.

if your are just printing to the screen the following pseudo code will show how to print the heading only when it changes

current_heading = ""
for each row in results
    if row.heading not equal to current_heading   
        current_heading  = row.heading
        print blank line 
        print current_heading 
    end if
    print row.value
loop

Upvotes: 2

Seasoned
Seasoned

Reputation: 1049

IN MS SQL, it can be achieved as follows:

    declare @sql nvarchar(max)
declare @col_name varchar(100)
select @col_name = heading from tbl_info where heading = 'greetings'
set @sql = 'select col_1 as ' + quotename(@col_name) + ' from component_psar'
exec(@sql)

However, this solution is a code snippet and not one single query.

Upvotes: -1

Related Questions