SQL 竖表变横表

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

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

那么变横表后,就变成:

支付宝微信
15080

这里介绍另一种情况,使用场景是,把按 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(α/β)BatchValue
2910
2920
2812
2822

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

Batchαβ
1 0
12 
22 
2 0

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

Batchαβ
120
220

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值