簡體   English   中英

如何從一個連接語句中的左表中獲取所有行?

[英]How to get all rows from left table in a join statement?

我有兩張桌子。 一個是Employee_Mstr ,另一個是EmployeeLeaveRequest_mstr

我的資料:

我的資料

使用GROUP BY

select t1.emp_cd, t1.emp_name, sum(t2.num_dy) from 
  Employee_Mstr t1 left join 
  EmployeeLeaveRequest_mstr t2 on t1.emp_cd = t2.emp_cd group by t1.emp_cd, t2.emp_name;
SELECT tab1.emp_cd, tab1.emp_name, SUM(tab2.num_dy)
FROM Employee_Mstr tab1, "2nd Table Records" tab2
where tab1.emp_cd = tab2.emp_cd
group by tab1.emp_cd, tab1.emp_name;

應該起作用,只需為第二張表設置正確的表名。

pk emp_cd用作主鍵,然后使用left join加入故事。 然后,您可以使用sumof添加值,在添加值之前使用groupby

如果需要,請訪問w3school.com。

select mstr.Emp_cd, mstr.Emp_Name, isnull(sum(det.num_dy), 0) as num_day
from dbo.Employee_Mstr mstr
left join dbo.Employee_Nums det on (mstr.Emp_cd = det.Emp_cd)
group by mstr.Emp_cd, mstr.Emp_Name;

應該做的工作。

這是SQL執行的結果:

Emp_cd      Emp_Name
----------- --------------------------------------------------
1           A
2           B
3           C

(3 row(s) affected)

Emp_cd      num_dy
----------- -----------
3           4
3           2

(2 row(s) affected)

Emp_cd      Emp_Name                                           num_day
----------- -------------------------------------------------- -----------
1           A                                                  0
2           B                                                  0
3           C                                                  6
Warning: Null value is eliminated by an aggregate or other SET operation.

(3 row(s) affected)

嘗試這個:

select t1.cd, t1.name, sum(t2.num_dy) from employee_Mstr t1 
left join EmployeeLeaveRequest_mstr t2 on t1.cd = t2.cd group by t1.cd, t1.name;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM