sqlserver行列转换

一、使用sum(case when)

废话不多说,直接上图

select projectDeclare_id,
            sum(case when seq=0 then score1 else NULL end) as 'diyihang',
            sum(case when seq=1 then score1 else NULL end) as 'diyihang',
            sum(case when seq=2 then score1 else NULL end) as 'diyihang',
            sum(case when seq=3 then score1 else NULL end) as 'diyihang',
            sum(case when seq=4 then score1 else NULL end) as 'diyihang',
            sum(case when seq=5 then score1 else NULL end) as 'diyihang',
            sum(case when seq=6 then score1 else NULL end) as 'diyihang',
            sum(case when seq=7 then score1 else NULL end) as 'diyihang',
            sum(case when seq=8 then score1 else NULL end) as 'diyihang',
            sum(case when seq=9 then score1 else NULL end) as 'diyihang',
            sum(case when seq=10 then score1 else NULL end) as 'diyihang',
            sum(case when seq=11 then score1 else NULL end) as 'diyihang',
            sum(case when seq=12 then score1 else NULL end) as 'diyihang',
            sum(case when seq=13 then score1 else NULL end) as 'dierhang'
from (
SELECT
    * 
FROM
    Lab_Performance lp 
WHERE
    lp.projectDeclare_id IN (
SELECT
    pd.id 
FROM
    Pro_Declare pd
    LEFT JOIN pro_main pm ON pm.id = pd.projectMain_id
    LEFT JOIN Pro_Plan pp ON pp.id = pm.projectPlan_id 
WHERE
    pp.projectname LIKE '%孵化器统计绩效%' 
    AND pd.uniCode LIKE '%绩效_2022_二季度%' 
    )
) as b group by projectDeclare_id

需要用到行列转换的表一般都会用到三个字段

1、表中表示同一组数据的字段,我这里就是declare_id

2、需要分列的字段数据,就是转换成行之后的字段,我这里用的是seq

3、不同seq对应的数据,这个可以有很多个,多用几个case when 就行

sum(case when seq='?' then score else NULL end) as '字段名'

by the way,这里面select ..from(select..) as b这里需要有一个as 可能是子查询需要命名吧

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值