sql查询结果横向显示?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sql查询结果横向显示?相关的知识,希望对你有一定的参考价值。

正常的查询结果是图1,想要实现的效果是图2,当图1的查询结果有1000行,那图2就要显示1000列。

简单啊,先用row_number 获取 No顺序,然后通过  STUFF FOR XML PATH 获取顺序号转成字段

 通过动态SQL利用PIVOT行列

参考技术A Select fgroup,max(case when nid=1 then fnum else null end) as fnum1,max(case when nid=2 then fnum else null end) as fnum2,max(case when nid=3 then fnum else null end) as fnum3,max(case when nid=4 then fnum else null end) as fnum4,max(case when nid=5 then fnum else null end) as fnum5from table group by fgroup本回答被提问者采纳

sql复杂的子查询,横向合并结果集

第一个查询的结果集

select * from(
select c.msName,a.msId,c.msPrice, c.msPrice*COUNT(a.msId) as totalMoney,sum(a.msAmount) as totalCount    from BillConsume a right join 
 (select top 1 msTime as startTime,GETDATE() as endTime from BillConsume where DateDiff(dd,msTime,getdate())=0  order by msTime asc) b on a.msTime between b.startTime and b.endTime and a.msId!=0
left join Menus c on c.msId=a.msId   group by a.msId ,c.msName,c.msPrice)s

连接两个结果集的语句

 full join 

第二个查询的结果集

(select sum(t.totalMoney) as allTotalMoney   from (
 select c.msName,a.msId,c.msPrice, c.msPrice*COUNT(a.msId) as totalMoney,sum(a.msAmount) as totalCount  from BillConsume a right join 
 (select top 1 msTime as startTime,GETDATE() as endTime from BillConsume where DateDiff(dd,msTime,getdate())=0  order by msTime asc) b on a.msTime between b.startTime and b.endTime and a.msId!=0
left join Menus c on c.msId=a.msId   group by a.msId ,c.msName,c.msPrice)t)t

连表的条件

on 1=1

 

以上是关于sql查询结果横向显示?的主要内容,如果未能解决你的问题,请参考以下文章

sql查询结果拼接

SQL Server常用查询

sql语句:将两个查询结果关联显示

SQL如何显示查询结果的前100条?

sql语句中如何 查询结果显示中间几行

SQL如何显示查询结果的前100条?