Splitting/Pivot Data from a Date Range using SQL

后端 未结 2 632
执念已碎
执念已碎 2021-01-16 18:44

Hi I have a problem with regarding on split/pivot dates

Here is my query

select Name
     , Start
     , End 
  from Employees 
 where St         


        
2条回答
  •  甜味超标
    2021-01-16 19:16

    First, create the table as -

    USE `Test`;
    CREATE  TABLE `test`.`Tbl_Sample_Data` (
      `Name` VARCHAR(50) NULL ,    
      `Start` DATETIME NULL ,
      `End` DATETIME NULL );
    

    Insert rows using -

    INSERT INTO `test`.`tbl_sample_data`
    (`End`,
    `Name`,
    `Start`)
    VALUES
    (
    'PutEndDateHere',
    'PutNameHere',
    'PutStartDateHere'
    );
    

    Here, dates should be in yyyy-MM-dd format, otherwise you get error 1292.

    Use this query to get what you want.

    SELECT `Name`,'Start' AS colName, `Start` AS value FROM test.tbl_sample_data
    UNION ALL
    SELECT `Name`,'End' AS colName, `End` AS value FROM test.tbl_sample_data
    ORDER BY `Name` ASC
    

    Note that column names whose name is the same as a keyword must be enclosed in backticks. Eg. Example Name. Otherwise, you get error.

提交回复
热议问题