sql server怎么行转列

sql server怎么行转列,第1张

PIVOT 用于将列值旋转为列名(即行转列),在 SQL Server 2000可以用聚合函数配合CASE语句实现

PIVOT 的一般语法是:PIVOT(聚合函数(列) FOR 列 in (…) )AS P

注意:PIVOT、UNPIVOT是SQL Server 2005 的语法,使用需修改数据库兼容级别(在数据库属性->选项->兼容级别改为 90 )

SQL2008 中可以直接使用

完整语法:

table_source

PIVOT(

聚合函数(value_column)

FOR pivot_column

IN(<column_list>)

)

View Code

UNPIVOT 用于将列明转为列值(即列转行),在SQL Server 2000可以用UNION来实现

完整语法:

table_source

UNPIVOT(

value_column

FOR pivot_column

IN(<column_list>)

)

select kldm,

sum(case when shy=520100 then cnt_kldm else 0 end) [520100],

sum(case when shy=520101 then cnt_kldm else 0 end) [520101]

from 表名

group by kldm

如果“站名”、“条码”、“时间”都是一样的话,可以这么写:

with

t_temp as (select row_number() over (partition by station_name order by param_name asc) id, t from t),

t_temp1 as (select from t_temp where id = 1),

t_temp2 as (select from t_temp where id = 2),

t_temp3 as (select from t_temp where id = 3)

select '站名' col1, '条码' col2, t_temp1参数名 col3, t_temp2参数名 col4, t_temp3参数名 col5, '时间' col6

from t_temp1, t_temp2, t_temp3

where t_temp1站名 = t_temp2站名

and t_temp2站名 = t_temp3站名

union all

select t_temp1站名, t_temp1条码, to_char(t_temp1数值), to_char(t_temp2数值), to_char(t_temp3数值), to_char(t_temp1时间)

from t_temp1, t_temp2, t_temp3

where t_temp1站名 = t_temp2站名

and t_temp2站名 = t_temp3站名

以上就是关于sql server怎么行转列全部的内容,包括:sql server怎么行转列、怎么用SQL语句将表中的行转换成列、ORAClE sql如何实现行转列等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/sjk/9548267.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-29
下一篇 2023-04-29

发表评论

登录后才能评论

评论列表(0条)

保存