如何连接两个表来获得此输出 [英] How to join two tables to get this output
本文介绍了如何连接两个表来获得此输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
第一张桌子
EMPID CODEID金额
0157 C 0
0157 F 0
0157 L 0
0157 M 0
0157 T 0
0737 C 0
0737 F 0
0737 L 0
0737 M 0
0737 T 0
第二张桌子
EMPID CODEID TOTAL_PAID_AMT
0157 T 4174.10
0737 C 5565.93
如何连接这两个表,使第二个表有5行,因为第一个表有5行。
只有一个非零值需要在第二个表中非匹配行应该为零。
每个empid有5个代码ID,所以最后的o / p需要显示5行。
如果第2个表中有一些数量,那么它应该是显示其他明智的0需要显示。
我尝试过:
从第一个f中选择*,第二个s
其中f.empid = s.empid
和f.codeid = s.codeid
顺序1
解决方案
除了 OriginalGriff [ ^ ],我强烈建议您阅读这篇文章: SQL连接的可视化表示 [ ^ ]
尝试:
SELECT f.EMPID,
f.CODEID,
ISNULL(s.TOTAL_PAID_AMT, 0 )
FROM FirstTable f
LEFT JOIN SecondTable s
ON f.EMPID = s.EMPID AND f.CODEID = s.CODEID
First table EMPID CODEID amount 0157 C 0 0157 F 0 0157 L 0 0157 M 0 0157 T 0 0737 C 0 0737 F 0 0737 L 0 0737 M 0 0737 T 0
second table EMPID CODEID TOTAL_PAID_AMT 0157 T 4174.10 0737 C 5565.93
How to join these two tables such that second table has 5 rows because first has 5 rows.
Only one non zero values needs to be in second table non-matching rows should be zero.
There are 5 code id for each empid so respective 5 rows needs to displayed in final o/p.
If some amount is present in 2nd table then it should be shown other wise 0 needs to be displayed.
What I have tried:
select * from first f, second s
where f.empid=s.empid
and f.codeid=s.codeid
order by 1
解决方案
In addition to solution1 by OriginalGriff[^], i'd strongly recommend to read this article: Visual Representation of SQL Joins[^]
Try:
SELECT f.EMPID, f.CODEID, ISNULL(s.TOTAL_PAID_AMT, 0) FROM FirstTable f LEFT JOIN SecondTable s ON f.EMPID = s.EMPID AND f.CODEID = s.CODEID
这篇关于如何连接两个表来获得此输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文