这也许很简单,但我不知道。基本上我将C#linq查询转换为sql查询以减少执行时间。但是我不擅长sql查询,所以我发现很难。这是我的两个桌子及其记录
HRMS_EodRecord
SELECT EmployeeId,HRMS_EodReferenceFk,ActualAmount FROM HRMS_EodRecord
结果如下:
EmployeeId HRMS_EodReferenceFk ActualAmount
101 1 1000
101 2 999
101 3 0
和另一个桌子
HRMS_EodReference
SELECT ID FROM HRMS_EodReference
结果如下:
ID
1
2
3
4
5
我想将这两个表的数据和结果相结合
EmployeeId HRMS_EodReferenceFk ActualAmount
101 1 1000
101 2 999
101 3 0
101 4 0 ----From HRMS_EodReference
101 5 0 ----From HRMS_EodReference
答案 0 :(得分:0)
在2个表中有关EmployeeId的相关信息不足,但这可以帮助您入门:
SELECT rec.EmployeeId --> Insufficient info on relationship
, ref.ID AS HRMS_EodReferenceFk
, CASE WHEN rec.ActualAmount IS NULL THEN 0 ELSE rec.ActualAmount END
AS ActualAmount
FROM HRMS_EodReference AS ref
LEFT JOIN HRMS_EodRecord AS rec ON rec.HRMS_EodReferenceFk = ref.ID;
答案 1 :(得分:0)
您可能正在寻找SQL“右连接”,编号:https://www.w3schools.com/sql/sql_join_right.asp
RIGHT JOIN关键字返回右表(表2)中的所有记录,并返回左表(表1)中的匹配记录。如果没有匹配项,则结果从左侧为NULL。
SELECT HRMS_EodRecord.EmployeeId, HRMS_EodReference.ID, HRMS_EodRecord.ActualAmount FROM HRMS_EodRecord
RIGHT JOIN HRMS_EodReference ON HRMS_EodRecord.HRMS_EodReferenceFk = HRMS_EodReference.ID
答案 2 :(得分:0)
如果您只有一个员工ID,
select 101 as EmployeeId,
ref.ID as HRMS_EodReferenceFk
coalesce(rec.ActualAmount, 0) as ActualAmount
from HRMS_EodReference ref left join
HRMS_EodRecord rec
on rec.HRMS_EodReferenceFk = ref.ID;
不过,大概您一次想要许多员工使用。在这种情况下,请使用cross join
生成行,然后使用left join
引入现有值:
select e.EmployeeId,
ref.ID as HRMS_EodReferenceFk
coalesce(rec.ActualAmount, 0) as ActualAmount
from (select distinct EmployeeId
from HRMS_EodRecord
) cross join
HRMS_EodReference ref left join
HRMS_EodRecord rec
on rec.EmployeeId = e.EmployeeId and
rec.HRMS_EodReferenceFk = ref.ID;