将SQL查询转换为LINQ to Entities

时间:2012-04-01 09:36:25

标签: sql-server linq

我有一个特殊情况,我使用LINQ-SQL编写代码,但我会这样做...但问题是我无法转换它!任何人都可以帮我一把吗?感谢

这是查询

插入

SET NOCOUNT ON;
USE tempdb;
GO
CREATE TABLE dbo.Employe (
  Id int NOT NULL PRIMARY KEY,
  Name varchar(10) NOT NULL
  );
CREATE TABLE dbo.Customer (
  Id int NOT NULL PRIMARY KEY,
  Name varchar(10) NOT NULL
  );
CREATE TABLE dbo.Movement (
  Id int NOT NULL IDENTITY PRIMARY KEY,
  EmployeeId int NOT NULL,
  CustomerId int NOT NULL,
  Data date NOT NULL,
  Time int NOT NULL,
  SpecialCost decimal(18,4) NULL
  );
CREATE TABLE dbo.EmployeeCost (
  EmployeeId int NOT NULL,
  Data date NOT NULL,
  Value decimal(18,4) NOT NULL
  );
GO
INSERT INTO dbo.Customer
  VALUES ( 1, 'Cli1' ), ( 2, 'Cli2' ), ( 3, 'Cli3' );
INSERT INTO dbo.Employe
  VALUES ( 1, 'Mirko' ), ( 2, 'Andrea' );
INSERT INTO dbo.EmployeeCost
  VALUES ( 1, '20110101', 1 ), ( 1, '20110701', 1.5 ), ( 1, '20120101', 2 );

INSERT INTO dbo.EmployeeCost
  VALUES ( 2, '20110101', 1 ), ( 2, '20120101', 1.3 );

INSERT INTO dbo.Movement
  VALUES ( 1, 1, '20110301', 2, NULL )  
    , ( 2, 1, '20110501', 1, NULL )  
    , ( 1, 1, '20110801', 1, NULL ) 
    , ( 2, 1, '20111001', 1, NULL ) 
    , ( 2, 1, '20120201', 1, 0.5 ); 


GO

现在查询

USE tempdb;
GO
WITH cte AS (
  SELECT c.EmployeeId, c.Data, c.Value
    , ROW_NUMBER() OVER (PARTITION BY EmployeeId ORDER BY Data) AS [r]
    FROM dbo.EmployeeCost c
  ),
cteCost AS (
  SELECT ec.EmployeeId, ec.Data, ec.Value
    , ISNULL(DATEADD(DAY, -1, c.Data), '20991231') AS NextDate
    FROM cte ec
      LEFT JOIN cte c ON ec.EmployeeId = c.EmployeeId
        AND c.r = ec.r +1
  )
SELECT c.Id, c.Name
  , m.Data, d.Name, m.Time AS [Time], ec.Value AS [Cost per Hour], m.SpecialCost
  , m.Time * ISNULL(m.SpecialCost, ec.Value) AS [Employe Cost]
  FROM dbo.Customer c
    JOIN dbo.Movement m ON m.CustomerId = c.Id
    JOIN dbo.Employe d ON m.EmployeeId = d.Id
    JOIN cteCost ec 
      ON ec.EmployeeId = m.EmployeeId
        AND m.Data BETWEEN ec.Data AND ec.NextDate;
GO

任何人都可以帮助我吗?感谢

编辑:结果查询

--<----------------
Id           Customer   Data       Employe   Time     Cost per hour  Total Cost

1           Cli1       2011-03-01   Mirko      2            1.0000              2.0000000000
1           Cli1       2011-05-01   Andrea     1            1.0000                  1.0000000000
1           Cli1       2011-08-01   Mirko      1            1.5000                  1.5000000000
1           Cli1       2011-10-01   Andrea     1            1.0000                 1.0000000000
1           Cli1       2012-01-15   Mirko      1            2.0000          
1           Cli1       2012-02-01   Andrea     1            1.3000        0.5000000000

1 个答案:

答案 0 :(得分:0)

我没有看到任何需要传递给CTE语句的参数,因此您可以create a view将其映射到模型中。

然后您可以像访问任何其他表一样访问该视图。

修改

create view dbo.vwEmployeeCosts as 

;WITH cte AS (
    ...
)
select *
   ...
from

然后在模型中映射此视图,就像使用表格

一样