SQL 竖表变横表

竖表变横表的情况,大多数是要将数据分组,然后用一行显示所有组的数据。比如:

支付方式 支付金额
支付宝 100
微信 20
支付宝 50
微信 60

那么变横表后,就变成:

支付宝 微信
150 80

这里介绍另一种情况,使用场景是,把按 key - value 形式存储的数据,用 key 的各种值作为表头,显示在 UI 上。

直接看代码看示例吧:

    declare  @col1 nvarchar(100) = 'ns=2;s=MySLR.Dv1.DB OPC UA.Other Equipment.Irradiation Values α'
	declare  @col2 nvarchar(100) = 'ns=2;s=MySLR.Dv1.DB OPC UA.Other Equipment.Irradiation Values β'

    --表一,原数据表
	select p.Id as 'Id(α/β)',d.Batch as Batch,Value as 'Value'
	from [DSC].[CollectionData] d inner join [DSC].[CollectionPoint] p on d.CollectionPointId = p.Id
	where 
	Batch is not null and Batch <> '' 
	and (TagName = @col1 or TagName = @col2)
    
    --表二,给表添加数据类型列
	select d.Batch as Batch,
	case when p.TagName = @col1 then Value else '' end as α,
	case when p.TagName = @col2 then Value else '' end as β 
	into #sourceTmp
	from [DSC].[CollectionData] d inner join [DSC].[CollectionPoint] p on d.CollectionPointId = p.Id
	where 
	Batch is not null and Batch <> '' 
	and (TagName = @col1 or TagName = @col2)

	select * from #sourceTmp order by Batch
    
    --表三,合并 Batch 相同的。
	select Batch,
	stuff((select '' + α from  #sourceTmp t where Batch = #sourceTmp.Batch for xml path(''))
	,1,0,'') as α,
	stuff((select '' + β from  #sourceTmp t where Batch = #sourceTmp.Batch for xml path(''))
	,1,0,'') as β
	from #sourceTmp
	group by Batch
	order by Batch

	drop table #sourceTmp

上面 SQL 得到的三张表如下:

表一:原数据表,我们的目标是,相同Batch的数据,按Id不同,显示在一行。

Id(α/β) Batch Value
29 1 0
29 2 0
28 1 2
28 2 2

表二:给表添加数据类型列,得到要显示的表结构。

Batch α β
1   0
1 2  
2 2  
2   0

表三:合并 Batch 相同的,得到最终横表。

Batch α β
1 2 0
2 2 0

你可能感兴趣的:(数据库,sql,竖表变横表,分组)