SQL server JOIN查询无法正常工作

时间:2015-10-12 04:47:11

标签: sql-server-2008 sql-server-2012

您好我对sql server

有疑问

部门

+---------+--------+
| deptkey | deptno |
+---------+--------+
|    1    |  100   |
|    2    |  101   |
|    3    |  -1    |
+---------+--------+

LOC

+--------+-------+
| lockey | locid |
+--------+-------+
|   1    |  200  |
|   2    |  201  |
|   3    |  -1   |
+--------+-------+

+----+--------+-------+------+
| id | deptno | locid | Name |
+----+--------+-------+------+
| 1  |  100   |  201  | abc  |
| 2  |  101   |  203  | def  |
| 3  |  103   |  200  | rav  |
| 4  |  105   |  204  | jai  |
| 1  |  101   |  200  | kal  |
| 4  |  100   |  206  | lo   |
+----+--------+-------+------+

这里tran deptno = dept.deptno然后相应的键值带来如果不匹配那么我们需要unmatched deptno assign -1和相应的键需要反向 类似的tran locid = loc.locid

基于上面的表我想要输出如下

+----+------+---------+--------+
| id | Name | deptkey | lockey |
+----+------+---------+--------+
| 1  | abc  |    1    |   2    |
| 2  | def  |    2    |   3    |
| 3  | rav  |    3    |   1    |
| 4  | jai  |    3    |   3    |
| 1  | kal  |    2    |   1    |
| 4  | lo   |    1    |   3    |
+----+------+---------+--------+

我尝试过以下查询

SELECT a.[id],a.name ,b.deptkey,c.lockey
  FROM [trans] a  left join dept b on a.deptno=b.deptno 
  left join  loc c on a.locid=c.locid

上面的查询没有给出预期的结果你能告诉我如何在sql server中编写查询来实现这个任务

3 个答案:

答案 0 :(得分:0)

SELECT a.[id],a.name ,b.deptkey,c.lockey 

FROM [trans] a  left join dept b on isnull(a.deptno,-1)=isnull(b.deptno,-1) 
  left join  loc c on a.locid=c.locid

试试这个...

答案 1 :(得分:0)

SELECT 
   a.[id]
   , a.name 
   , ISNULL(b.deptkey,-1) AS [deptkey]
   , ISNULL(b.lockey,-1) AS [lockey]
  FROM [trans] a  
  left join dept b 
      on a.deptno = b.deptno 
  left join  loc c 
      on a.locid = c.locid

如果找不到值ISNULL,请将结果更改为-1而不是NULL。您只需将-1与您偏好的任何default value更改为无法匹配。

如果您需要查询驱动的默认值(将最后一条记录作为默认值),则为OR。您可以更改脚本,如下所示。

SELECT 
   a.[id]
   , a.name 
   , ISNULL(b.deptkey,(SELECT TOP 1 deptno from dept ORDER BY deptkey DESC)) AS [deptkey]
   , ISNULL(b.lockey,(SELECT TOP 1 locid from loc ORDER BY lockey DESC)) AS [lockey]
  FROM [trans] a  
  left join dept b 
      on a.deptno = b.deptno 
  left join  loc c 
      on a.locid = c.locid

答案 2 :(得分:0)

 SELECT a.[id],a.name ,
    (CASE WHEN b.deptkey IS NULL THEN (select deptkey from DEPT WHERE DeptNo = -1) 
       ELSE b.deptkey END) AS 'deptkey',
    (CASE WHEN c.lockey IS NULL THEN (select LocKey from LOC WHERE LocId = -1) 
       ELSE c.lockey END) AS 'lockey '
 FROM [trans] a  left join dept b on a.deptno=b.deptno 
 left join  loc c on a.locid=c.locid

http://www.sqlfiddle.com/#!3/389463/2