日期:2014-05-18 浏览次数:20511 次
CREATE TABLE #(Qty INT,Employee NVARCHAR(200)) INSERT # SELECT 30, N'小王、小李、小张' INSERT # SELECT 20, N'小王、小李' INSERT # SELECT 40, N'小张' GO SELECT Employee, Qty=SUM(Qty) FROM ( SELECT substring(a.Employee,b.number,charindex(N'、',a.Employee+N'、',b.number)-b.number) AS Employee,Qty FROM (SELECT Employee,Qty=Qty/(LEN(Employee)-len(REPLACE(Employee,N'、',''))+1) FROM #) AS a,master.dbo.spt_values AS b WHERE b.type='P' AND charindex(N'、',N'、'+a.Employee,b.number)=b.number )T GROUP BY Employee /* Employee Qty 小李 20 小王 20 小张 50 */
------解决方案--------------------
--弄错了,我以为求和呢
select 人员,sum(数量) as 数量 from ( select substring(a.人员, b.number, charindex(',', a.人员 + ',', b.number) - b.number) as 人员 , 数量/(len(a.人员) - len(replace(a.人员, ',', '')) + 1) as 数量 from T a join master.dbo.spt_values b on b.type = 'p' and substring(','+ a.人员, b.number,1) = ',' and b.number between 1 and len(a.人员) ) x group by 人员 /* 人员 数量 ------------------ ----------- 小李 20 小王 20 小张 50 */