sql

Posted 菜鸟级程序猿

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sql相关的知识,希望对你有一定的参考价值。

行转列不留空 

SELECT  \'A\' AS [订单号],\'四川\' AS [地址] INTO #Result
 INSERT INTO #Result
 SELECT  \'A\' AS [订单号],\'成都\' AS [地址]
 UNION ALL 
 SELECT  \'B\' AS [订单号],\'新疆\' AS [地址]
 UNION ALL 
 SELECT  \'B\' AS [订单号],\'喀什\' AS [地址]
 UNION ALL 
 SELECT  \'B\' AS [订单号],\'和田\' AS [地址]

 SELECT CAST(ROW_NUMBER() OVER(PARTITION BY [订单号] ORDER BY [地址]) AS NVARCHAR(256)) AS num,[订单号],[地址] INTO #Table FROM #Result GROUP BY [订单号],[地址]

 DECLARE @sql NVARCHAR(MAX)
 set @sql = \'select [订单号] \'
 select @sql = @sql + \' , max(case [num] when \'\'\' + num + \'\'\' then [地址] else \'\'\'\' end) [地址]\' from (select DISTINCT num FROM #Table) as a
 set @sql = @sql + \' from #Table group by  [订单号]\'
 EXEC (@sql)

 DROP TABLE #Result
 DROP TABLE #Table

 

行转列,行做列头


 SELECT  \'A\' AS [订单号],\'四川\' AS [地址] INTO #Result
 INSERT INTO #Result
 SELECT  \'A\' AS [订单号],\'成都\' AS [地址]
 UNION ALL 
 SELECT  \'B\' AS [订单号],\'新疆\' AS [地址]
 UNION ALL 
 SELECT  \'B\' AS [订单号],\'喀什\' AS [地址]
 UNION ALL 
 SELECT  \'B\' AS [订单号],\'和田\' AS [地址]

 SELECT * FROM #Result

 DECLARE @sql NVARCHAR(MAX)
 set @sql = \'select [订单号] \'
 select @sql = @sql + \' , max(case [地址] when \'\'\' + [地址] + \'\'\' then [地址] else \'\'\'\' end) [\'+[地址]+\']\' from (select DISTINCT [地址] FROM #Result) as a
 set @sql = @sql + \' from #Result group by  [订单号]\'
 EXEC (@sql)

 DROP TABLE #Result

 

以上是关于sql的主要内容,如果未能解决你的问题,请参考以下文章

sql [sql技巧]一些sql技巧#sql

sql 2008 r2 在sql 2008上兼容么

SQL基础

有大神知道,sql server 中如何批量执行sql语句吗?

pl sql developer怎么执行sql

pl sql developer怎么执行sql