2015-09-22 77 views
-1

想象一下,我有一個像下面的表,我想寫一個查詢,給我下面的結果,這有可能嗎?寫下表查詢

enter image description here

結果:

100 , 2015-01-01 , ABC , XYZ 
+0

是數據中的任何變化 – wiretext

+0

解釋更多信息,請 – SajjadZare

+1

也許你應該定義你的需求更確切地說。現在它太模糊了。另外 - 你是否自己嘗試過任何東西,或者是「爲我寫代碼」請求? –

回答

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

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