mySQL查询语句行转列横向显示

mySQL查询语句行转列横向显示,第1张

我仅提供思路给你,至于其它单位,可以单独摘录出来,union all

select 始发地 目的地 起步价,sum(case when 区间 > 0 and 区间 <= 20 then 单位价格 else '' end) '0-20(公斤)' ,

sum(case when 区间 > 20 and 区间 <= 50 then 单位价格 else '' end) '20-50(公斤)' ,

sum(case when 区间 > 50 and 区间 <= 100 then 单位价格 else '' end) '50-100(公斤)' from (你的sql语句) t group by t始发地 ,t目的地 ,t起步价

一般这样的情况 如果是我做的话 就预先建立一个表 设置time1 time1 time3……

然后 分别逐次以 no 和日期为 time 分组 ;行标题 time 为列标题 和 值(求和)……对先前建立的表进行追加……

SQL 我不太熟悉 在access 中 完全可以做的……

还有 如果 你能够 把你的时间 划分成不同的时间段 而对应到固定的时间段中的话,完全 直接可以使用 一个交叉查询就可以了……

但愿 这个提示 对你有所帮助……

使用CASE来处理。

select 编号, sum( 第一季度第一次施肥量) 第一季度第一次施肥量, sum( 第一季度第二次施肥量) 第一季度第二次施肥量, sum( 第二季度第一次施肥量) 第二季度第一次施肥量

from

(

select 编号

case when 季度=1 and 施肥次数=1 then 施肥量 else null end 第一季度第一次施肥量,

case when 季度=1 and 施肥次数=2 then 施肥量 else null end 第一季度第二次施肥量,

case when 季度=2 and 施肥次数=1 then 施肥量 else null end 第二季度第一次施肥量

from 表

) a

group by a编号

例子如下:

create table tb(姓名 varchar(10) , 课程 varchar(10) , 分数 int)

Insert tb

Select '张三','语文',60 union all

Select '张三','数学',70 union all

Select '张三','英语',80 union all

Select '张三','物理',90 union all

Select '李四','语文',65 union all

Select '李四','数学',75 union all

Select '李四','英语',85 union all

Select '李四','物理',95

go

declare @sql varchar(8000)

set @sql = ''

select @sql = @sql+[课程]+'=sum(case when [课程]='''+[课程]+''' then [分数] else 0 end),' from (SELECT DISTINCT [课程] FROM TB) A

--print @sql

set @sql = left(@sql,len(@sql) - 1)

set @sql = 'select [姓名]=max([姓名]), '+@sql+' from tb group by [姓名] '

print @sql

exec (@sql)

--drop table t

select [姓名]=max([姓名]),

数学=sum(case when [课程]='数学' then [分数] else 0 end),

物理=sum(case when [课程]='物理' then [分数] else 0 end),

英语=sum(case when [课程]='英语' then [分数] else 0 end),

语文=sum(case when [课程]='语文' then [分数] else 0 end)

from tb group by [姓名]

结果:

李四 75 95 85 65

张三 70 90 80 60

以上就是关于mySQL查询语句行转列横向显示全部的内容,包括:mySQL查询语句行转列横向显示、SQL里面如何将竖着的列横着显示、SQL 竖列 转换横列的问题等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!

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

原文地址: http://outofmemory.cn/sjk/10161747.html

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

发表评论

登录后才能评论

评论列表(0条)

保存