DECLARE @S NVARCHAR(1000) SELECT @S='SELECT [USER_NAME] AS 姓名' SELECT @S=@S+',SUM(CASE WHEN COURSE='''+CAST(COURSE AS VARCHAR)+'''THEN SCORE END) AS '+COURSE FROM TEST_TB_GRADE GROUP BY COURSE SELECT @S=@S+' FROM TEST_TB_GRADE GROUP BY [USER_NAME]' EXEC(@S) --这一句怎么没有select SUM(CASE WHEN COURSE='''+CAST(COURSE AS VARCHAR)+'''THEN SCORE END) AS '+COURSE FROM TEST_TB_GRADE GROUP BY COURSE
简化下: [USER_NAME] AS 姓名=姓名,‘SUM(CASE WHEN COURSE='''+CAST(COURSE AS VARCHAR)+'''THEN SCORE END) AS '+COURSE =COURSE,
SELECT @S='SELECT 姓名,COURSE FROM TEST_TB_GRADE GROUP BY COURSE and GROUP BY [USER_NAME]'
兄弟,你这一搞我跟看不懂了。。。。。。
@小银光: AS用法知道吧!就是 查询[USER_NAME] AS(名称作为) 姓名。简化查询。这个sql语句就是查询USER_NAME和COURSE从TEST_TB_GRADE 表中。最后按照COURSE和USER_NAME进行分组查询。这么个逻辑。
@卿君: 我自己已经想明白了。
SELECT @S=@S+',SUM(CASE WHEN COURSE='''+CAST(COURSE AS VARCHAR)+'''THEN SCORE END) AS '+COURSE FROM TEST_TB_GRADE GROUP BY COURSE
这个FROM对应的是前面的SELECT,这个SELECT是查询的作用,
@S=@S+是将查询的值拼成一个字符串!
@小银光: 恩恩,是的
这是拼接一个T-sql的字符串
拼接的sql中不是有 select啊
虽然这么说,但他有两个FROM!