行转列

Posted xiaohu666

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了行转列相关的知识,希望对你有一定的参考价值。

列转行:利用max(case when then),不转行的列作为group by 的条件

技术图片

SELECT
    `name`,
    MAX(
        CASE 
        WHEN  course=语文 THEN
            score
        END
    ) AS 语文,
    MAX(
        CASE 
        WHEN course=数学 THEN
            score
        END
    ) AS 数学, 
    MAX(
        CASE 
        WHEN course=英语 THEN
            score
        END
    ) AS 英语
FROM
    student
GROUP BY `name`
;

 

技术图片

合并字段显示:利用group_cancat(course,”:”,”score”)

技术图片

 

 不过行转列用decode()也行   DECODE与MAX的联合使用

SELECT DISTINCT EMP_NO,MAX(DECODE(TO_CHAR(WORK_DATE,DD),01,CARD_FREQUENCY)) D01,
MAX(DECODE(TO_CHAR(WORK_DATE,DD),02,CARD_FREQUENCY)) D02,
MAX(DECODE(TO_CHAR(WORK_DATE,DD),03,CARD_FREQUENCY)) D03,
MAX(DECODE(TO_CHAR(WORK_DATE,DD),04,CARD_FREQUENCY)) D04,
MAX(DECODE(TO_CHAR(WORK_DATE,DD),05,CARD_FREQUENCY)) D05,
MAX(DECODE(TO_CHAR(WORK_DATE,DD),06,CARD_FREQUENCY)) D06,
MAX(DECODE(TO_CHAR(WORK_DATE,DD),07,CARD_FREQUENCY)) D07,
MAX(DECODE(TO_CHAR(WORK_DATE,DD),08,CARD_FREQUENCY)) D08,
MAX(DECODE(TO_CHAR(WORK_DATE,DD),09,CARD_FREQUENCY)) D09,
MAX(DECODE(TO_CHAR(WORK_DATE,DD),10,CARD_FREQUENCY)) D10,
MAX(DECODE(TO_CHAR(WORK_DATE,DD),11,CARD_FREQUENCY)) D11,
MAX(DECODE(TO_CHAR(WORK_DATE,DD),12,CARD_FREQUENCY)) D12,
MAX(DECODE(TO_CHAR(WORK_DATE,DD),13,CARD_FREQUENCY)) D13,
MAX(DECODE(TO_CHAR(WORK_DATE,DD),14,CARD_FREQUENCY)) D14, 
MAX(DECODE(TO_CHAR(WORK_DATE,DD),15,CARD_FREQUENCY)) D15,
MAX(DECODE(TO_CHAR(WORK_DATE,DD),16,CARD_FREQUENCY)) D16
FROM HRA_READ_CARD_MONTH 
WHERE EMP_NO=090641 AND TO_CHAR(WORK_DATE,YYYY/MM)=2009/03
GROUP BY EMP_NO

 

以上是关于行转列的主要内容,如果未能解决你的问题,请参考以下文章

SQL Server 动态行转列(参数化表名分组列行转列字段字段值)

MySQL 行转列 -》动态行转列 -》动态行转列带计算

Oracle数据 行转列

MySQL行转列与列转行

PIVOT:行转列函数

SQLSERVER有张表,需要每晚自动实现行转列。