为这个表写一个查询

时间:2015-09-22 11:23:43

标签: sql-server tsql

想象一下,我有一个像下面这样的表,我想写一个查询给我下面的结果,是否可能?

enter image description here

结果:

100 , 2015-01-01 , ABC , XYZ

2 个答案:

答案 0 :(得分:3)

您可以使用PIVOT

<强>查询

select userid, 
[date],
[job],
[address]
from
(
    select userid,name,[value] from tblName
)
as s
pivot 
(
   max([value]) for [name] in ([date], [job], [address])
) as p;

SQL Fiddle

<强> OR

<强>查询

select userid,
max(case when name = 'date' then [value] else null end) as [date],
max(case when name = 'job' then [value] else null end) as job,
max(case when name = 'address' then [value] else null end) as address
from tblName
group by userid;

SQL Fiddle

答案 1 :(得分:0)

另一种方式,

尝试使用Group_ConcatenateCommon Table Expression

;with cte as

(select userid,
STUFF((
 SELECT ',' + md.[value]
 FROM tblName md
 WHERE m.userid = md.userid
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
as result
from tblName m group by m.userid
)

select (cast(userid as varchar(50))+','+result) as res from cte

请参阅Demo Here