douzhi8244 2015-10-08 05:15
浏览 136
已采纳

工资表的MY SQL查询

I have 3 tables in MYSQL From 2 different database running in same server

enter image description here

and my expected Output is

enter image description here

MY attempt of query is

SELECT `biometric`.`Empid`,
,`name`,`location`,`basic`,`hra`,`conveyance`,`total salary`,sum(DISTINCT DATEDIFF(LEAST(`endDate`,'$monthEnd' ),GREATEST(`startdate`,'$monthStart'))+1) as leaves FROM `biometric`.`biometric`,`biometric`.`employee` JOIN `lms`.`leaves` WHERE `biometric`.`empid`= `employee`.`empid` AND `employee`.`empid` = `leaves`.`id` AND  
`startdate`<='$monthEnd' AND `endDate`>= '$monthStart' AND `leaves`.`status` = '3'
GROUP BY `Empid`

and here status =3 is approved leave and 1 is non approved leave. and my out put coming is

enter image description here Thanks in Advance...

  • 写回答

1条回答 默认 最新

  • dongyan1993 2015-10-08 05:51
    关注

    You can try below query, even I did not test it so if you get any error then you can create an sqlfiddle so that I can correct it.

    Basic concept is that you need to use left join for lms.leaves table as you need all employee details even they did not took leave under status 3.

    SELECT bmt.`Empid`,`name`,`location`,`basic`,`hra`,`conveyance`,`total salary`,
    IFNULL(SUM(DISTINCT DATEDIFF(LEAST(`endDate`,'$monthEnd' ),GREATEST(`startdate`,'$monthStart'))+1),0) AS LEAVES 
    FROM BM.`biometric` AS bmt
    JOIN BM.`employee` AS emp ON bmt.`empid`= emp.`empid`
    LEFT JOIN `lms`.`leaves` AS lvs ON emp.`empid` = lvs.`id` AND lvs.`status` = '3' AND `startdate`<='$monthEnd' AND `endDate`>= '$monthStart' 
    GROUP BY bmt.`Empid`;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?