0
点赞
收藏
分享

微信扫一扫

mysql 自定义 PIVOT函数

在MySQL中,没有内置的PIVOT函数,但你可以使用CASE语句和聚合函数来实现类似的结果。以下是一个简单的例子:

假设我们有一个sales表,结构如下:

+----+-----+-------+| id | day | sales |+----+-----+-------+|  1 | Mon |   100 ||  1 | Tue |   150 ||  2 | Mon |    80 ||  2 | Wed |   120 |+----+-----+-------+
+----+-----+-------+| id | day | sales |+----+-----+-------+|  1 | Mon |   100 ||  1 | Tue |   150 ||  2 | Mon |    80 ||  2 | Wed |   120 |+----+-----+-------+

我们想要将day字段的不同值转换为列,可以这样写:

SELECT   id,  MAX(CASE WHEN day = 'Mon' THEN sales ELSE NULL END) AS 'Mon',  MAX(CASE WHEN day = 'Tue' THEN sales ELSE NULL END) AS 'Tue',  MAX(CASE WHEN day = 'Wed' THEN sales ELSE NULL END) AS 'Wed'FROM salesGROUP BY id;
SELECT   id,  MAX(CASE WHEN day = 'Mon' THEN sales ELSE NULL END) AS 'Mon',  MAX(CASE WHEN day = 'Tue' THEN sales ELSE NULL END) AS 'Tue',  MAX(CASE WHEN day = 'Wed' THEN sales ELSE NULL END) AS 'Wed'FROM salesGROUP BY id;

这将输出:

+----+-----+-----+-----+| id | Mon | Tue | Wed |+----+-----+-----+-----+|  1 | 100 | 150 | NULL||  2 |  80 | NULL| 120 |+----+-----+-----+-----+
+----+-----+-----+-----+| id | Mon | Tue | Wed |+----+-----+-----+-----+|  1 | 100 | 150 | NULL||  2 |  80 | NULL| 120 |+----+-----+-----+-----+

这个查询通过CASE语句对sales字段进行转换,根据day字段的值将数据转置。然后使用GROUP BY对id进行分组,以确保每个id只出现一次。

SELECT  plant_id,workshop,date_
		,count(c0) as count0
		,count(c1) as count1
		,count(c2) as count2
		,count(c3) as count3
		,count(c4) as count4
		,count(c5) as count5
	
from
   ( select 
		 a.plant_id
		,a.workshop
		,a.date_
		,case when a.priority_sort = 0 then  a.priority_sort   end  c0
		,case when a.priority_sort = 1 then  a.priority_sort   end  c1
		,case when a.priority_sort = 2 then  a.priority_sort   end  c2
		,case when a.priority_sort = 3 then  a.priority_sort   end  c3
		,case when a.priority_sort = 4 then  a.priority_sort   end  c4
		,case when a.priority_sort = 5 then  a.priority_sort   end  c5
		from 
		(SELECT plant_id,workshop
		,NOW() as date_
		,IFNULL(po_priority_sort, 0) AS priority_sort
		FROM pdm_production_order) a
	) b
group by workshop,plant_id



举报

相关推荐

0 条评论