CREATE TABLE ck(dm varchar(10), mc varchar(20))<br>GO<br>INSERT INTO ck(dm, mc) select '1', '仓库A'<br>UNION ALL SELECT '2', '仓库B'<br>UNION ALL SELECT '3', '仓库C'<br>GO<br>CREATE TABLE kc(bh varchar(10), mc varchar(20),<br> ckdm varchar(10), sl numeric(18, 2))<br>GO <br>INSERT INTO kc(bh, mc, ckdm, sl) <br>SELECT '1001','铅笔', '1', 10<br>UNION ALL SELECT '1001', '铅笔', '2', 6<br>SELECT * FROM KC<br>GO<br>SELECT * FROM ck<br>GO<br><br>DECLARE @s varchar(8000)<br>SELECT @s = ''<br>SELECT @s = @s + ',' + char(13) + <br> '[' + mc + '] = sum(case kc.ckdm when ''' + dm + ''' then isnull(sl, 0) else 0 end)'<br>FROM ck<br>PRINT @s <br><br>exec('SELECT bh, kc.mc , sum(isnull(sl, 0)) sl' + @s + ' FROM ck, kc where ck.dm = kc.ckdm group by kc.bh, kc.mc')<br>GO<br>//------------------结果.<br>1001 铅笔 16.00 10.00 6.00 .00