有表A 里面的数据这样(字段)
datamonth type value
201507 upper 1
201508 upper 2
201509 upper 3
201510 upper 4
想要把它的datamonth 字段横向显示转换成月份如下 (数据没有默认为0)
type jan feb mar ...... Jul aug sep oct nov dec
upper 0 0 0 ...... 1 2 3 4 0 0
该怎么做,有点头痛,求大神解救!
我想把datamonth 的那一列转成横(字段),然后再把数据对上去,随datamonth 列字段可以动态的生产横(字段)
这个应该是行列转换,sql中有专门的函数来实现,mysql不知道有没有
就sql,有个pivot函数,还是不行。
@搁忆: 你确定是sql呀,那我写个试试
@MrNice: 恩,谢谢先
@搁忆:
SELECT [Type],ISNULL([201501],0) AS Jan,ISNULL([201502],0) AS Feb,ISNULL([201503],0) AS Mar,ISNULL([201504],0) AS Apr, ISNULL([201505],0) AS Mar,ISNULL([201506],0) AS Jun,ISNULL([201507],0) AS Jul,ISNULL([201508],0) AS Aug, ISNULL([201509],0) AS Sep,ISNULL([201510],0) AS Oct,ISNULL([201511],0) AS Nov,ISNULL([201512],0) AS [Dec] FROM(SELECT * FROM monthinfo PIVOT( SUM(value) FOR DateMonth in([201501],[201502],[201503],[201504],[201505],[201506],[201507],[201508],[201509],[201510],[201511],[201512]) ) AS PVT) P
@搁忆: 不好意思没法动态生成,你的需求满足不了
@MrNice: in 里面能不能是个selec 语句,因为我的数据很多比喻(select distinct datamonth from 表A )可惜报错
@搁忆: in 中必须是固定的
@MrNice: 哦
SELECT type ,
sum(CASE datamonth WHEN '201507' THEN value ELSE 0 END) Jul,
sum(CASE datamonth WHEN '201508' THEN value ELSE 0 END) aug,
sum(CASE datamonth WHEN '201509' THEN value ELSE 0 END) sep,
sum(CASE datamonth WHEN '201510' THEN value ELSE 0 END) oct
FROM 表A
group by type
谢谢
想要动态生成的话只能用存储过程中拼接sql的方式
DECLARE @sql_str NVARCHAR(MAX)
DECLARE @sql_col NVARCHAR(MAX),@TotalNo NVARCHAR(MAX)
DECLARE @tableName SYSNAME --行转列表
DECLARE @groupColumn SYSNAME --分组字段
DECLARE @row2column SYSNAME --行变列的字段
DECLARE @row2columnValue SYSNAME --行变列值的字段
SET @tableName = 'XX'--需要改变的表名
SET @groupColumn = '字段1,字段2,字段3,字段4,字段5,。。。'--固定的字段
SET @row2column = '动态列名'
SET @row2columnValue = '动态列名对应的值'
SET @sql_str = N'
SELECT @sql_col_out = ISNULL(@sql_col_out + '','','''') + QUOTENAME(['+@row2column+'])
FROM ['+@tableName+'] GROUP BY ['+@row2column+']'
--PRINT @sql_str
EXEC sp_executesql @sql_str,N'@sql_col_out NVARCHAR(MAX) OUTPUT',@sql_col_out=@sql_col OUTPUT
--PRINT @sql_col
SET @sql_str = N'
SELECT * into #newpdate FROM (
SELECT '+@groupColumn+',['+@row2column+'],['+@row2columnValue+'] FROM ['+@tableName+']) p PIVOT
(SUM(['+@row2columnValue+']) FOR ['+@row2column+'] IN ( '+ @sql_col +') ) AS pvt
'
print(@sql_str)---打印输出
exec(@sql_str)--运行存储过程