sql纵列数据查询后展示为横向数据

场景

需要统计不同类别的数据,并展示为横向数据。
例如:
统计公司不同类别产品的销售额。

解决方案

一开始看到有些蒙。其实很简单,用if 或者 case即可。

sql中直接解决

select 
	sum(
	case category 
	when 'Alcohol' then amount
	end
	) as AlcoholAmount,
	sum(
	case category 
	when 'smoke' then amount
	end
	) as SmokeAmount 
from sales
where company='a-company'
group by category

这样返回的字段直接对应值了,用实体类接收即可。

返回列表,在代码中进行加工

select 
category,sum(amount) as totalAmount
from sales
where company='a-company'
group by category

这样可以返回个map,然后在java进行遍历。根据类型放到实体类中也是可以的。

猜你喜欢

转载自blog.csdn.net/enthan809882/article/details/114006881