t-sql中pivot用法(行列转换)

从另一张表找的3974行是张三,8319行是李四,3051行是王五;

从stu_score查id,stu_id两列,聚合求出 得出张三,李四,王五在stu_score中的记录条数 

复制代码
select   [ 3974 ]   as  张三,  [ 8319 ]   as  李四,  [ 3051 ]   as  王五
from  
(
select  id,stu_id  from  stu_score)  as  s
pivot
(
    
count (id)
    
for  stu_id  in  ( [ 3974 ] , [ 8319 ] , [ 3051 ] )
)
as  pvt
复制代码

 

 T-SQL Pivot Syntax

SELECT

  [non-pivoted column], -- optional

  [additional non-pivoted columns], -- optional

  [first pivoted column],

  [additional pivoted columns]

FROM (

  SELECT query producing sql data for pivot

  -- select pivot columns as dimensions and

  -- value columns as measures from sql tables

) AS TableAlias

PIVOT

(

  <aggregation function>(column for aggregation or measure column) -- MIN,MAX,SUM,etc

  FOR [<column name containing values for pivot table columns>]

  IN (

    [first pivoted column], ..., [last pivoted column]

  )

) AS PivotTableAlias

 

复制代码
select  exam_name  as  考试名称,  [ 407 ]   as  一班,  [ 408 ]   as  二班,  [ 409 ]   as  三班,  [ 415 ]   as  九班
from
(
select  dept_id, exam_name,  [ language ]  
from  stu_score,stu_studentinfo 
where  stu_score.stu_id  =  stu_studentinfo.id)  as  t
pivot
(
    
avg ( [ language ] )
    
for  dept_id  in  ( [ 407 ] , [ 408 ] , [ 409 ] , [ 415 ] )
)
as  pvt
复制代码

结果如下:

考试名称一班二班三班九班
考试一89.2688.3390.3685.25
考试二82.2687.9880.3685.25
期末81.2683.3380.3678.25
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值