I have this huge table(not of my own making) where data has been dumped in with very little structure. It has 5 columns abcde of which only a, b and c interest me in this case. a is an int id column(not unique) b is attrib_code (string) c is attrib_val (anything int, string, null whatever)
my issue is I'm trying to get a two column answer based on where clauses but both columns are subsets of column c.
I want my first column to be the result of
SELECT attrib_val (and if nessisary id)
FROM table_name
WHERE attrib_code = 'stringA'
second column
SELECT attrib_val (and if nessisary id)
FROM table_name
WHERE attrib_code = 'stringB'
where id=id
I'm using Microsoft SQL Server Management Studio 2008 and I have tried to create both those tables as views but I keep getting an error saying: "Create View must be the only statement in the batch"
Any Help with this would be greatly appreciated.
Thanks
You can do this using a join
:
SELECT coalesce(ta.id, tb.id) as id, ta.attrib_val as aval, tb.attrib_val as bval
from (select ta.*
from table_name ta
where ta.attrib_code = 'stringA'
) ta full outer join
(select tb.*
from table_name tb
where tb.attrib_code = 'stringB'
) tb
on ta.id = tb.id ;
The full outer join allows you to get id
s that have only one value set.
You can also do this with conditional aggregation:
select id,
max(case when attrib_code = 'stringA' then attrib_value end) as aval,
max(case when attrib_code = 'stringG' then attrib_value end) as bval
from table_name
where attrib_code in ('stringA', 'stringB')
group by id;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.