时间:2021-07-01 10:21:17 帮助过:4人阅读
较为复杂的实例
具体实现代码
--创建表 GO CREATE TABLE #T1( NAME NVARCHAR(100), CHINESE NVARCHAR(100), MATH NVARCHAR(100), ENGLISH NVARCHAR(100) ) --插入模拟数据 SELECT * FROM #T1 GO INSERT INTO #T1 VALUES(‘张三‘,80,90,90) INSERT INTO #T1 VALUES(‘李四‘,47,78,null) INSERT INTO #T1 VALUES(‘王五‘,null,90,null) GO SELECT * FROM #T1 --具体代码实现 GO SELECT * FROM ( SELECT NAME AS ‘姓名‘,‘语文‘ AS ‘科目‘,CHINESE AS ‘成绩‘ FROM #T1 UNION ALL SELECT NAME AS ‘姓名‘,‘数学‘ AS ‘科目‘,MATH AS ‘成绩‘ FROM #T1 UNION ALL SELECT NAME AS ‘姓名‘,‘英语‘ AS ‘科目‘,ENGLISH AS ‘成绩‘ FROM #T1 ) T order by T.姓名
解决方法二
--列转行的静态方案:UNPIVOT,sql2005及以后版本
--方法二;这个方法 会自动去除值为 NULL 的值 SELECT NAME,OBJ,GRADE FROM #T1 UNPIVOT(GRADE FOR OBJ IN (CHINESE,MATH,ENGLISH)) AS UP
网络上 还流行这个方法
INFORMATION_SCHEMA.COLUMNS视图中获取列来构造行,同样也使用了XML处理。
2 列转行
简单实例
CREATE TABLE #T0 ( MON1 INT ) INSERT INTO #T0 VALUES(1) INSERT INTO #T0 VALUES(2) INSERT INTO #T0 VALUES(3) SELECT * FROM #T0 --方法一 仅仅限制于 数据不重复的情况下 SELECT (SELECT MON1 FROM #T0 WHERE MON1=1) ‘1‘, (SELECT MON1 FROM #T0 WHERE MON1=2) ‘2‘, (SELECT MON1 FROM #T0 WHERE MON1=3) ‘3‘
sql中的行转列和列转行的问题
标签: