我有两个表,如下所示,需要加入两个表,需要获取结果表。
有人可以帮我吗?
New_Table
Emp CodeEmp Name BF OOF TB
11111 AAAA Y Off 1
22222 BBBB Y Off 0.75
22222 BBBB Y Off 0.25
33333 CCCC Y On 0.98
44444 DDDD Y Off 1
55555 EEEE Y Off 1
Old_Table
Emp Code Emp Name BF OOF TB
11111 AAAA Y Off 1
22222 BBBB Y Off 0.25
22222 BBBB Y Off 0.75
33333 CCCC Y Off 0.98
Result
Emp Code Emp Name BF OOF TB
44444 DDDD Y Off 1
55555 EEEE Y Off 1
我已经尝试了下面的SQL查询购买我得到的Emp Code 222222我不需要,因为Emp Code 222222的TB总和相等,即1 = 1.
INSERT INTO Result ([Emp Code]
,[Emp Name]
,[BF]
,[OOF]
,[TB])
SELECT a.[Emp Code]
,a.[Emp Name]
,a.[BF]
,a.[OOF]
,a.[TB]
FROM New_Table a left join Old_Table b
on a.[Emp Code] = b.[Emp Code] where
a.[BF] = 'Y' and a.[OOF] = b.[OOF] and a.[TB] > b.[TB]
and a.[TB] > 0.5 ;
答案 0 :(得分:0)
使用SUM,GROUP BY和HAVING子句。
INSERT INTO Result ([Emp Code]
,[Emp Name]
,[BF]
,[OOF]
,[TB])
SELECT a.[Emp Code]
,a.[Emp Name]
,a.[BF]
,a.[OOF]
,sum(a.[TB])
FROM New_Table a left join Old_Table b
on a.[Emp Code] = b.[Emp Code] where
a.[BF] = 'Y' and a.[OOF] = b.[OOF]
and a.[TB] > 0.5
group by
a.[Emp Code]
,a.[Emp Name]
,a.[BF]
,a.[OOF]
having sum(a.[TB]) > sum(b.[TB])
答案 1 :(得分:0)
试试这个:
AND (a.TB + COALESCE(B.TB, 0)) != 1
这将为你消除22222。
或者,您可以尝试子查询。
and a.[Emp Code] not in (select [Emp Code] from New_Table group by [Emp Code]
having sum(TB) = 1)
您可以将任何where子句限制添加到您需要的子查询中。
答案 2 :(得分:0)
USE EXCEPT
运营商查找新记录。
我只修改了你的查询。你能试试下面的代码吗?
INSERT INTO Result ([Emp Code]
,[Emp Name]
,[BF]
,[OOF]
,[TB])
SELECT a.[Emp Code]
,a.[Emp Name]
,a.[BF]
,a.[OOF]
,a.[TB]
FROM New_Table a left join Old_Table b
on a.[Emp Code] = b.[Emp Code] where
a.[BF] = 'Y' and a.[OOF] = b.[OOF] and a.[TB] > b.[TB]
group by a.[Emp Code]
,a.[Emp Name]
,a.[BF]
,a.[OOF]
,a.[TB]
having sum(a.tb)>1