sqlserver 行转列 列转行

本文展示了行转列和列转行的操作方法,包括一个实际案例,涉及数据的转换和分析。
部署运行你感兴趣的模型镜像

---行转列
declare @abc table(col1 varchar(20),col2 varchar(20))
insert @abc
select 'A','ddd' union all
select 'B','asdf' union all
select 'C','dsdf' union all
select 'D','eee' union all
select 'E','geas' union all
select 'F','2' union all
select 'G','5d' union all
select 'H','sad' union all
select 'I','ww' union all
select 'J','23' union all
select 'K','asdfw'

select  ib.A,ib.B,ib.C,ib.D,ib.E,
ib.F,ib.G,ib.H,ib.I,ib.J,ib.K
from @abc ia pivot
(
    max(col2)  for col1 in(A,B,C,D,E,F,G,H,I,J,K)
) ib


----列转行
declare @unpivot table(col1 varchar(20),col2 varchar(20))
declare @RowTransfercolumn table(A varchar(20),B varchar(20),C varchar(20),
D varchar(20),E varchar(20),F varchar(20),G varchar(20),H varchar(20),
I varchar(20),J varchar(20),K varchar(20))
insert @RowTransfercolumn(A,B,C,D,E,F,G,H,I,J,K)
select 'ddd','asdf','dsdf','eee','geas','2','5d','sad','ww','23','asdfw'
select col1,col2 from @RowTransfercolumn ia
unpivot(
    col2 for col1 in(A,B,C,D,E,F,G,H,I,J,K)
 
) ie

 

行转列、列传行的综合案例:

/*
  报3门科
    总人数:2人
    通过3门:1人(50%)
    通过2门:0人(50%)
    通过1门:1人(50%)
    通过0门:0人(50%)           
*/

declare @table table(name varchar(255),num varchar(10),score int)
insert into @table(name,num,score)
select '张三' ,'01',100 union all
select '张三' ,'02',90  union all
select '张三' ,'03',60  union all
select '李四' ,'01',100 union all
select '李四' ,'02',50  union all
select '李四' ,'03',50  union all
select '王五' ,'03',100

select I4.col1 as [标题],I4.col2 as [PassPerson] from (
select
 (I2.[0]+I2.[1]+I2.[2]+I2.[3]) as [总人数],
 i2.[3] as [通过3门],
 i2.[2] as [通过2门],
 i2.[1] as [通过1门],
 i2.[0] as [通过0门]
from (
select
    name,
    count(case when score>=60  then num end) as [Pass]
from @table where name in ( select name from @table  group by name  having(count(num) =3)
)group by name
) I1  pivot 
(
  count(name) for Pass in ([0],[1],[2],[3])
)I2
) I3  unpivot
(
   col2 for col1 in ([总人数],[通过3门],[通过2门],[通过1门],[通过0门])
) I4

 

 

您可能感兴趣的与本文相关的镜像

Dify

Dify

AI应用
Agent编排

Dify 是一款开源的大语言模型(LLM)应用开发平台,它结合了 后端即服务(Backend as a Service) 和LLMOps 的理念,让开发者能快速、高效地构建和部署生产级的生成式AI应用。 它提供了包含模型兼容支持、Prompt 编排界面、RAG 引擎、Agent 框架、工作流编排等核心技术栈,并且提供了易用的界面和API,让技术和非技术人员都能参与到AI应用的开发过程中

评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值