我将数据从SQL加载到CSV文件。我的csv记录采用以下方式。
Eid ename desig sourceD location
1 Ralf PM 1 UK
1 Ralf PM 1 USA
2 Marty PL 3 GBR
3 Levis BA 5 UK
4 Ricky BI 7 RSA
4 Ricky BI 7 FRA
现在我想将EID 1和4组合成单行。我的输出必须采用以下方式
Eid ename desig sourceD location
1 Ralf PM 1 UK, USA
2 Marty PL 3 GBR
3 Levis BA 5 UK
4 Ricky BI 7 RSA, FRA
我只有CSV文件我没有任何SQL查询或任何东西。
答案 0 :(得分:2)
SQL查询
select c1.Eid, c1.ename,c1.desig,c1.sourceD,
( SELECT x.location + ', '
FROM Contacts x
WHERE c1.Eid = x.Eid
ORDER BY x.location
FOR XML PATH ('')
) as Locations
from Contacts c1
group by c1.Eid, c1.ename,c1.desig,c1.sourceD
工作?
如果你想在最后没有逗号:
SELECT c1.Eid, c1.ename,c1.desig,c1.sourceD,
LEFT( ( SELECT x.location + ', '
FROM Contacts x
WHERE c1.Eid = x.Eid
ORDER BY x.location
FOR XML PATH ('')
),LEN(( SELECT x.location + ', '
FROM Contacts x
WHERE c1.Eid = x.Eid
ORDER BY x.location
FOR XML PATH ('')
))-1) AS Locations
FROM Contacts c1
GROUP BY c1.Eid, c1.ename,c1.desig,c1.sourceD
此查询将让您避免长度0:
SELECT c1.Eid, c1.ename,c1.desig,c1.sourceD,
LEFT( ( SELECT x.location + ', '
FROM Contacts x
WHERE c1.Eid = x.Eid
ORDER BY x.location
FOR XML PATH ('')
),CASE WHEN LEN(( SELECT x.location + ', '
FROM Contacts x
WHERE c1.Eid = x.Eid
ORDER BY x.location
FOR XML PATH ('')
))=0 THEN 1 ELSE LEN(( SELECT x.location + ', '
FROM Contacts x
WHERE c1.Eid = x.Eid
ORDER BY x.location
FOR XML PATH ('')
)) END -1) AS Locations
FROM Contacts c1
GROUP BY c1.Eid, c1.ename,c1.desig,c1.sourceD