Search code examples
sql-serversql-server-2008pivotentity-attribute-value

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

Solution

  • 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, '');