我有一张桌子:
表1
fname lname job education
----------------------------------------
john doe dentist harvard
john doe dentist mit
eric doyle lawyer mit
anna johnson nurse yale
尝试选择所有列
select fname, lname, job, education
from table1
但这会返回输出
john doe dentist harvard
john doe dentist mit
eric doyle lawer mit
anna johnson nurse yale
我怎么能这样做:
john doe dentist harvard, mit
eric doyle lawer mit
anna johnson nurse yale
换句话说,同一个人“john doe”,教育被连成一列一行。
正在考虑编写一个Python脚本:
需要一些提示!提前谢谢。
答案 0 :(得分:1)
试试这个:
CREATE TABLE #Table1(fname VARCHAR(20), lname VARCHAR(20),job VARCHAR(20),education VARCHAR(20))
INSERT INTO #Table1
SELECT 'john', 'doe' ,'dentist', 'harvard' UNION ALL
SELECT 'john', 'doe' ,'dentist', 'mit' UNION ALL
SELECT 'eric', 'doyle' ,'lawer' , 'mit' UNION ALL
SELECT 'anna', 'johnson' ,'nurse' , 'yale'
SELECT T1.fname,T1.lname,T1.job,
STUFF(( SELECT ', ' + cast(T2.education as varchar(5))
FROM #Table1 T2
WHERE T1.fname = T2.fname AND T1.lname = T2.lname
FOR XML PATH('')
), 1, 2, '') as education
FROM #Table1 T1
GROUP BY T1.fname,T1.lname,T1.job
答案 1 :(得分:0)
您需要使用1,1值作为教育
select fname, lname, job, stuff ((
select ',' + education from #Table1 where fname = t.fname and lname = t.lname and job = t.job
for xml path('')
),1,1,'') as education
from #Table1 t
group by fname, lname, job