日期:2014-05-16 浏览次数:20642 次
select code,
MAX(case when line = 'IAL' THEN GlsCount else 0 end) 'IAL',
MAX(case when line = 'IBL' THEN GlsCount else 0 end) 'IBL',
MAX(case when line = 'ICL' THEN GlsCount else 0 end) 'ICL',
MAX(case when line = 'RWL' THEN GlsCount else 0 end) 'RWL'
from tb
group by code
我也刚开始学 我把各位大神的方法都试了下
CREATE TABLE GG(ID INT , LINE CHAR(10),CODE CHAR(20),GLSCOUNT INT , INPUT CHAR(20))
INSERT INTO GG
SELECT '1','IAL','0.7T PRO','1','20130412' UNION ALL
SELECT '2','IAL','0.5T DEV','3','20130413' UNION ALL
SELECT '3','ICL','0.7T DEV','1','20130414' UNION ALL
SELECT '4','RWL','0.5T PRO','1','20130415' UNION ALL
SELECT '5','IBL','0.5T DEV','2','20130416' UNION ALL
SELECT '6','IBL','0.7T DEV','2','20130417' UNION ALL
SELECT '7','IAL','0.5T PRO','1','20130418' UNION ALL
SELECT '8','IBL','0.5T DEV','1','20130419' UNION ALL
SELECT '9','IAL','0.7T DEV','2','20130420' UNION ALL
SELECT '10','ICL','0.5T DEV','1','20130421'
SELECT * FROM GG
GO
SELECT CODE,ISNULL(IAL,0) IAL,ISNULL(IBL,0) IBL,ISNULL(ICL,0) ICL ,ISNULL(RWL,0) RWL
FROM GG
PIVOT (MAX(GLSCOUNT) FOR LINE IN (IAL,IBL,ICL,RWL)
) J
SELECT ID,CODE,
MAX(CASE WHEN LINE='IAL' THEN GLSCOUNT ELSE 0 END ) IAL,
MAX(CASE WHEN LINE='IBL' THEN GLSCOUNT ELSE 0 END ) IBL,
MAX(CASE WHEN LINE='ICL' THEN GLSCOUNT ELSE 0 END ) ICL,
MAX(CASE WHEN LINE='RWL' THEN GLSCOUNT ELSE 0 END ) RWL
FROM GG
GROUP BY ID,CODE
ORDER BY 1
DECLARE @SQL VARCHAR(500)
SET @SQL ='SELECT ID,CODE'
SELECT @SQL =@SQL +',MAX(CASE WHEN LINE='''+line+''' THEN GLSCOUNT ELSE 0 END ) ['+line+']'
from (select distinct line from gg) a
set @SQL =@SQL +' FROM GG GROUP BY ID,CODE ORDER BY 1'
exec(@sql)