mysql:在一行中显示两行

时间:2011-01-14 05:57:25

标签: sql mysql

SELECT DATE_FORMAT(MAX(a.EffectiveDate),'%d-%m-%Y') AS `Date`,
       CONCAT(a.FirstNm,' ',IFNULL(a.MiidleNM,' '),' ',IFNULL(a.LastNM,' ')) AS `EmployeeName`, 
       `b`.`BranchName` AS `Branch`
  FROM `tbl_employeemaster` AS `a` 
  JOIN `tbl_branch` AS `b` ON a.BrnNm = b.idBranch     
UNION     
SELECT DATE_FORMAT(MAX(c.EffectiveDate),'%d-%m-%Y') AS `Date`,
       CONCAT(c.FirstNm,' ',IFNULL(c.MiidleNM,' '),' ',IFNULL(c.LastNM,' ')) AS `EmployeeName `, 
       `d`.`BranchName` AS `Branch`     
  FROM `tbl_employeehistory` AS `c`    
  JOIN `tbl_branch` AS `d` ON c.BrnNm = d.idBranch

...是输出:

Date        EmployeeName   Branch
-------------------------------------
15-01-2011  ABCD           Bangalore
10-10-2010  ABCD           Magalore

...但我希望输出如下所示

EmployeeName    Branch      Date        previous Branch     Date
ABCD        Bangalore       15-01-2011  Mangalore       10-10-2010

1 个答案:

答案 0 :(得分:0)

试试这个:

    SELECT a.EmployeeName,
           a.Branch,
           a.Date, b.branch previousBranch,
                   b.Date previousDate
    FROM
      ( SELECT DATE_FORMAT(MAX(a.EffectiveDate),'%d-%m-%Y') AS `Date`,
               CONCAT(a.FirstNm,' ',IFNULL(a.MiidleNM,' '),' ',IFNULL(a.LastNM,' ')) AS `EmployeeName`,
               `b`.`BranchName` AS `Branch`
       FROM `tbl_employeemaster` AS `a`
       INNER JOIN `tbl_branch` AS `b` ON a.BrnNm = b.idBranch) a
    LEFT JOIN
      (SELECT DATE_FORMAT(MAX(c.EffectiveDate),'%d-%m-%Y') AS `Date`,
              CONCAT(c.FirstNm,' ',IFNULL(c.MiidleNM,' '),' ',IFNULL(c.LastNM,' ')) AS `EmployeeName `,
              `d`.`BranchName` AS `Branch`
       FROM `tbl_employeehistory` AS `c`
       INNER JOIN `tbl_branch` AS `d` ON c.BrnNm = d.idBranch) b
   ON a.EmployeeName = b.EmployeeName