请帮助我查询,我有这个查询(见下文)
select
empnam as Emp_Name,seccod as DEPT,'' as REMARKS
,MAX(CASE WHEN STAT = 'IN' THEN clktim END)[IN]
,MAX(CASE WHEN STAT = 'OUT' THEN clktim END) OUT
from
(select a.clkid,
case when a.devid = '10' then 'IN' else 'OUT' end as STAT
, a.clkdat, a.clktim, b.empid, b.empnam, b.seccod,
row_number() over(partition by clkdat order by dateinsert) as seqnum
from ClkInf a
INNER JOIN EmpInf b ON a.clkid = b.clkid
where a.clkdat between (select FORMAT(getdate(), 'yyyyMMdd'))
and (select FORMAT(getdate() + 1, 'yyyyMMdd'))
and devid in (10, 50)
) mak
GROUP BY clkid,clkdat,empnam,seccod
order by DEPT ASC
导致图片
NAME DEPT IN OUT
Peter STP 647 NULL
Jordan FCW 647 NULL
Mark EE 724 NULL
Lebron STP NULL 810
Kobe STP NULL 813
Chris TR 729 NULL
Dray DC 705 NULL
如果有机会得到这个结果? 如果有什么查询我需要添加/更改?感谢
NAME DEPT IN OUT
Peter STP 647 NULL
Jordan FCW 647 NULL
Mark EE 724 NULL
Chris TR 729 NULL
Dray DC 705 NULL
答案 0 :(得分:1)
您可以添加HAVING
子句来检查您的情况output: IN not null and OUT is null
:
SELECT
empnam AS Emp_Name,seccod AS DEPT,'' AS REMARKS
,MAX(CASE WHEN STAT = 'IN' THEN clktim END)[IN]
,MAX(CASE WHEN STAT = 'OUT' THEN clktim END) OUT
FROM
(
SELECT a.clkid,
CASE WHEN a.devid = '10' THEN 'IN' ELSE 'OUT' END AS STAT
, a.clkdat, a.clktim, b.empid, b.empnam, b.seccod,
ROW_NUMBER() OVER (PARTITION BY clkdat ORDER BY dateinsert) AS seqnum
FROM ClkInf a
INNER JOIN EmpInf b ON a.clkid = b.clkid
WHERE a.clkdat BETWEEN (SELECT FORMAT(getdate(), 'yyyyMMdd'))
AND (SELECT FORMAT(getdate() + 1, 'yyyyMMdd'))
AND devid IN (10, 50)
) mak
GROUP BY clkid, clkdat, empnam, seccod
HAVING MAX(CASE WHEN STAT = 'IN' THEN clktim END) IS NOT NULL
AND MAX(CASE WHEN STAT = 'OUT' THEN clktim END) IS NULL
ORDER BY DEPT ASC;
答案 1 :(得分:0)
您必须再添加一个额外的FILTER条件:
select * from (
select
empnam as Emp_Name,seccod as DEPT,'' as REMARKS
,MAX(CASE WHEN STAT = 'IN' THEN clktim END) in_
,MAX(CASE WHEN STAT = 'OUT' THEN clktim END) OUT
from
(select a.clkid,
case when a.devid = '10' then 'IN' else 'OUT' end as STAT
, a.clkdat, a.clktim, b.empid, b.empnam, b.seccod,
row_number() over(partition by clkdat order by dateinsert) as seqnum
from ClkInf a
INNER JOIN EmpInf b ON a.clkid = b.clkid
where a.clkdat between (select FORMAT(getdate(), 'yyyyMMdd'))
and (select FORMAT(getdate() + 1, 'yyyyMMdd'))
and devid in (10, 50)
) mak
GROUP BY clkid,clkdat,empnam,seccod
order by DEPT ASC
) k
where in_ is not null;