Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

MySQL DML operation-the best way to achieve pivot row transfer function

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)06/01 Report--

1. Background

* since MySQL does not support column-column conversion between the pivot feature of type Oracle and SQL Server.

two。 Table and data

Mysql > select * from t_temp +-+ | year | season | orderCount | +-+ | 2010 | first quarter | 100 | | 2010 | second quarter | 200 | 2010 | third quarter | | 2010 | fourth quarter | 400 | 2011 | first quarter | 150 | 2011 | second quarter | 300 | 2011 | third quarter | 450 | 2011 | fourth quarter | 600 | +-+ 8 rows in set (0.00 sec)

3. It is realized by subquery and case when judgment

Mysql > select year, sum (orderCount1) 'first quarter',-> sum (orderCount2) 'second quarter',-> sum (orderCount3) 'third quarter',-> sum (orderCount4) 'fourth quarter'-> from-> (- > select year) -> case when season = 'first quarter' then-> orderCount-> end orderCount1,-> case when season = 'second quarter' then-> orderCount-> end orderCount2 -> case when season = 'third quarter' then-> orderCount-> end orderCount3,-> case when season = 'fourth quarter' then-> orderCount-> end orderCount4-> from t_temp->) t-> group by year +-+ | year | first quarter | second quarter | third quarter | fourth quarter | +- -+ | 2010 | 100 | 200 | 300 | 400 | | 2011 | 150 | 300 | 450 | 600 | +-- -+ 2 rows in set (0.00 sec)

4. Realized by IF aggregate function

Mysql > SELECT year,-> SUM (IF (season = 'first quarter', orderCount, null)) AS 'first quarter',-> SUM (IF (season = 'second quarter', orderCount, null)) AS 'second quarter',-> SUM (IF (season = 'third quarter', orderCount, null) AS 'third quarter',-> SUM (IF (season = 'fourth quarter', orderCount) Null)) AS 'fourth quarter'-> FROM t_temp-> GROUP BY year +-+ | year | first quarter | second quarter | third quarter | fourth quarter | +- -+ | 2010 | 100 | 200 | 300 | 400 | | 2011 | 150 | 300 | 450 | 600 | +-- -+ 2 rows in set (0.00 sec)

5. Summary

In order to demand-driven technology, there is no difference in technology itself, only in business.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report