• ADADADADAD

    MySQL DML操作--------实现pivot行转列功能最佳实战[ mysql数据库 ]

    mysql数据库 时间:2024-12-25 09:57:12

    作者:文/会员上传

    简介:

    1. 背景  * 由于MySQL 不支持类型Oracle与SQL Server的pivot功能进行行列转换。2. 表与数据mysql>select*fromt_temp;+---------+-----------+------------+|year|season|o

    以下为本文的正文内容,内容仅供参考!本站为公益性网站,复制本文以及下载DOC文档全部免费。

    1. 背景

      * 由于MySQL 不支持类型Oracle与SQL Server的pivot功能进行行列转换。

    2. 表与数据

    mysql>select*fromt_temp;+---------+-----------+------------+|year|season|orderCount|+---------+-----------+------------+|2010年|一季度|100||2010年|二季度|200||2010年|三季度|300||2010年|四季度|400||2011年|一季度|150||2011年|二季度|300||2011年|三季度|450||2011年|四季度|600|+---------+-----------+------------+8rowsinset(0.00sec)


    3. 通过子查询与case when判断实现

    mysql>selectyear,sum(orderCount1)'第一季度',->sum(orderCount2)'第二季度',->sum(orderCount3)'第三季度',->sum(orderCount4)'第四季度'->from->(->selectyear,->casewhenseason='一季度'then->orderCount->endorderCount1,->casewhenseason='二季度'then->orderCount->endorderCount2,->casewhenseason='三季度'then->orderCount->endorderCount3,->casewhenseason='四季度'then->orderCount->endorderCount4->fromt_temp->)t->groupbyyear;+---------+--------------+--------------+--------------+--------------+|year|第一季度|第二季度|第三季度|第四季度|+---------+--------------+--------------+--------------+--------------+|2010年|100|200|300|400||2011年|150|300|450|600|+---------+--------------+--------------+--------------+--------------+2rowsinset(0.00sec)


    4. 通过IF聚合函数实现

    mysql>SELECTyear,->SUM(IF(season='一季度',orderCount,null))AS'第一季度',->SUM(IF(season='二季度',orderCount,null))AS'第二季度',->SUM(IF(season='三季度',orderCount,null))AS'第三季度',->SUM(IF(season='四季度',orderCount,null))AS'第四季度'->FROMt_temp->GROUPBYyear;+---------+--------------+--------------+--------------+--------------+|year|第一季度|第二季度|第三季度|第四季度|+---------+--------------+--------------+--------------+--------------+|2010年|100|200|300|400||2011年|150|300|450|600|+---------+--------------+--------------+--------------+--------------+2rowsinset(0.00sec)


    5. 总结

    以需求驱动技术,技术本身没有优略之分,只有业务之分。

    MySQL DML操作--------实现pivot行转列功能最佳实战.docx

    将本文的Word文档下载到电脑

    推荐度:

    下载
    热门标签: mysqldbapivot