0

我正在尝试创建一个包含多个“With”语句的函数。

我原来的查询是:

WITH EmpCount as 
  (
    SELECT job.EmployeeID, assign.PropertyID FROM EmployeeJobstatus job 
    JOIN Assignment assign ON job.JobID = assign.ID  GROUP by job.EmployeeID,
    assign.PropertyID
  ),
    NoDup as 
  (
    SELECT EmployeeID, Count(employeeID) as NO from EmpCount 
    Group by EmployeeID HAVING count(Employeeid) > 1
  )

    SELECT prop.Name, job.EmployeeID, Emp.EmpID, Emp.Name 
    from EmployeeJobStatus job
    JOIN Assignment assign ON assign.id = job.jobid
    JOIN Property prop ON prop.ID = assign.PropertyID
    JOIN Employee emp on emp.ID = job.EmployeeID
    WHERE EmployeeID IN (SELECT EmployeeID from NoDup)
    GROUP By prop.Name, EmployeeID, emp.EmpID,Emp.Name
    Order BY EmployeeID

这将返回:

Name           EmployeeID   EmpID         Name
Property 1      23         1286333      LastNameRemoved1, Rachel A
Property 2      23         1286333      LastNameRemoved1, Rachel A
Property 2      76         1268329      LastNameRemoved2, Tamer A
Property 1      76         1268329      LastNameRemoved2, Tamer A
Property 3      135        1411933      LastNameRemoved3, Sarah E
Property 1      135        1411933      LastNameRemoved2, Sarah E

我的函数需要使用 EmployeeJobStatus StartDate 和 EndDate 中的字段,根据它们是否是交叉属性来返回“Y”或“N”。

我才刚刚开始我的功能,因为我不知道下一步该做什么。

CREATE function dbo.IsEmployeeCrossPropertyOnDate
 (@EmpID int, @AsOfDate datetime) 
  RETURNS INT AS

任何帮助,或朝着正确方向轻推将不胜感激。谢谢你。

4

1 回答 1

0

这个怎么样...

CREATE FUNCTION dbo.IsEmployeeCrossPropertyOnDate
    (
        @empid int
        , @asofdate datetime
    )
RETURNS TABLE
AS
RETURN
    SELECT
        CASE MIN(a.propertyid)
            WHEN MAX(a.propertyid)
                THEN 'N'
            ELSE 'Y'
        END CrossProp
    FROM 
        EmployeeJobStatus j
    JOIN 
        Assignment a
        ON a.id = j.jobid
    WHERE 
        j.employee = @empid
        AND j.startdate <= @AsOfDate
        AND j.endDate > @AsOfDate
    GROUP BY 
        j.employeeid;

编辑:

您可能会在外部应用它,而不是交叉。Nulls 将是当时没有任务的员工。

编辑2:

既然你问了,下面是一个标量函数。请注意标量。根据您在查询中使用它的位置,BEGIN END 块可以欺骗优化器进入 RBAR。

CREATE FUNCTION dbo.IsEmployeeCrossPropertyOnDate
    (
        @empid int
        , @asofdate datetime
    )
RETURNS CHAR(1)
AS
BEGIN
    DECLARE @res CHAR(1) = 'N';

    SELECT @res = 
        CASE MIN(a.propertyid)
            WHEN MAX(a.propertyid)
                THEN 'N'
            ELSE 'Y'
        END 
    FROM 
        EmployeeJobStatus j
    JOIN 
        Assignment a
        ON a.id = j.jobid
    WHERE 
        j.employee = @empid
        AND j.startdate <= @AsOfDate
        AND j.endDate > @AsOfDate
    GROUP BY 
        j.employeeid;

    RETURN @res;
END;
于 2012-12-06T22:53:59.350 回答