在单个sql查询中计算总存在和不存在的数量

时间:2015-04-21 10:08:52

标签: mysql sql-server

以下是我的出勤表详情Emp_ID(varchar),pdate(datetime),attendance(char(2))

enter image description here

我希望获得按emp_id

分组的特定日期范围的单个查询中的参与天数总数,缺席总数和当前总数

5 个答案:

答案 0 :(得分:3)

只是一个示例,向您展示如何继续处理数据

declare @t table (id int,da date,attend Varchar(2))
insert into @t (id,da,attend) values (1,'20141011','P'),
 (1,'20141012','A'),
  (1,'20141013','P'),
   (1,'20141014','A'),
   (1,'20141014','P')

   select ID,COUNT(da)Total,
   (select COUNT(da) from @t where attend = 'A')as Absent,
   (select COUNT(da) from @t where attend = 'P')as Present from @t
   group by id

答案 1 :(得分:3)

这对我有用。

select Emp_ID
      ,count(case when status ='A'  then 1 end) as absent_count
      ,count(case when status ='P' then 1 end) as present_count
      ,count(distinct pdate) as Tot_count
  from MASTERPROCESSDAILYDATA where pdate between '2014-01-01' and '2014-01-31' 
 group 
    by Emp_ID ;

答案 2 :(得分:1)

你应该尝试类似的东西

SELECT Emp_id, present, absent FROM details
NATURAL JOIN(
SELECT COUNT(*) AS present FROM details WHERE Emp_id = table.Emp_id AND attendence='P' 
JOIN
SELECT COUNT(*) AS absent FROM details WHERE Emp_id = table.Emp_id AND attendence='A' ) AS ctt

答案 3 :(得分:1)

您可以使用group by,如前所述。

或者您可以使用窗口函数/分析函数。

DECLARE @T TABLE (Emp_id INT,pdate DATE,attendance VARCHAR(2))
INSERT INTO @t (emp_id,pdate,attendance) VALUES (1,'20141011','P'),
 (1,'20141012','A'),
 (1,'20141013','P'),
 (1,'20141014','A'),
 (1,'20141014','P')


SELECT 
    DISTINCT
    EMP_ID,
    Attendance,
    COUNT(*) OVER (PARTITION BY attendance) as CntAttendance
FROM 
    @t

答案 4 :(得分:1)

尝试以下脚本;

select id,
       count(distinct pdate) as Total_Attendance_Days,
       sum(case when attendance= 'p' then 1 else 0 end) Presents,
      sum(case when att = 'a' then 1 else 0 end) Absents
from ##TT
where pdate between '01/04/2015' and '15/04/2015'
group by id 

希望这有帮助