Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pivot to obtain EAV data

I have an EAV table (simple key/value in every row) and I need to take the 'value' from two of the rows and concat them into a single row with a single column. I can't seem to get through the part where I just have the pivot straight. Can anyone help me figure this out?

Declare @eavHelp Table
(
    [Key]         VARCHAR (8)       NOT NULL,
    [Value]       VARCHAR (8)      NULL
)
Insert Into @eavHelp Values ( 'key1' , 'aaa' )    
Insert Into @eavHelp Values ( 'key2' , 'bbb' )

Select * From @eavHelp 
Pivot
(   Min( [Value] ) 
    For [Value] in ( hmm1 , hmm2 )
)
as Piv Where [Key] = 'key1' or [Key] = 'key2'

That makes:

Key      hmm1     hmm2
-------- -------- --------
key1     NULL     NULL
key2     NULL     NULL

But what I want to make is:

hmmmX
-----
aaa;bbb
like image 205
Snowy Avatar asked Mar 04 '26 09:03

Snowy


2 Answers

Don't really need to pivot.

EDIT to add new requirement (; delimiter):

SELECT hmmmX = STUFF((SELECT ';' + [Value] FROM @eavHelp 
    WHERE [Key] IN ('key1', 'key2')
    FOR XML PATH(''), TYPE).value(N'./text()[1]', N'varchar(max)'), 1, 1, '');
like image 137
Aaron Bertrand Avatar answered Mar 06 '26 00:03

Aaron Bertrand


Declare @eavHelp Table 
( 
    [Key]         VARCHAR (8)       NOT NULL, 
    [Value]       VARCHAR (8)      NULL 
) 
Insert Into @eavHelp Values ( 'key1' , 'aaa' )     
Insert Into @eavHelp Values ( 'key2' , 'bbb' ) 

declare @concat nvarchar(max); select @concat =''
select @concat =@concat+case when len(@concat)>0 then '; ' else '' end + value from    @eavHelp
select @concat
like image 21
Marcel Avatar answered Mar 05 '26 23:03

Marcel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!