根据表B中的内部或左连接选择数据

时间:2019-06-15 07:52:47

标签: sql sql-server tsql left-join inner-join

我有表A和表B 我想从带有一些联接和子句的表A(EmpID)中选择数据。 现在,我必须对表B(EMPID,NPINumber,NPIEndDate)应用联接,所有文件都是可选的。

但是条件是NPIEndDate是我们数据库中的可选字段,例如NPIEndDate is Null OR NPIEndDate > = CurrentDate现在写查询

1。如果NPINumber存在,则从A和B表中选择数据
2.如果NPIEndDate为Null或NPIEndDate> = CurrentDate

,则从A和B表中选择数据

CurrentDate为:27/06/2018

一张桌子:

+-------+
| EmpId |
+-------+
|     1 |
|     2 |
|     3 |
|     4 |
+-------+

B表:

+-------+-----------+------------+
| EMPID | NPINumber | NPIEndDate |
+-------+-----------+------------+
|     1 |      1001 | NULL       |
|     2 |      1234 | 27/04/2018 |
|     3 |     12345 | 27/06/2018 |
+-------+-----------+------------+

输出

+-------+-----------+------------+
| EMPID | NPINumber | NPIEndDate |
+-------+-----------+------------+
|     1 |      1001 | NULL       |
|     3 |     12345 | 27/06/2018 |
|     4 |           |            | 
+-------+-----------+------------+

4 个答案:

答案 0 :(得分:1)

您可以尝试以下方法:

SELECT 
      a.EMPID,b.NPINumber,b.NPIEndDate 
FROM A 
    LEFT JOIN B 
          ON a.EMPID=b.EMPID
WHERE ISNULL(b.NPIEndDate,GETDATE())>='2018-06-27 00:00:00.000'

答案 1 :(得分:0)

根据我的理解

SELECT 
 DATA 
FROM
  A
INNER JOIN B
ON (A.EmpID = B.EMPID AND (NPIEndDate <> '' or NPIEndDate is not null)

更新2: 根据您提供的数据

SELECT 
 DATA 
FROM
  A
INNER JOIN B
ON (A.EmpID = B.EMPID AND NPIEndDate >= CurrentDate AND (NPIEndDate = '' or NPIEndDate is null))

答案 2 :(得分:0)

这是一个简单的连接,其中包含WHERE子句中的某些条件

SELECT *
FROM A INNER JOIN B
ON A.EMPID = B.EMPID
WHERE B.NPIEndDate IS NULL
      OR
      B.NPIEndDate >= '2018-06-27';

例如:

SELECT *
FROM (VALUES (1), (2), (3)) A(EMPID) 
INNER JOIN 
(VALUES (1, 1001,NULL), (2, 1234,'2018-04-27'), (3, 12345,'2018-06-27'))B(EMPID, NPINumber, NPIEndDate)
ON A.EMPID = B.EMPID
WHERE B.NPIEndDate IS NULL
      OR
      B.NPIEndDate >= '2018-06-27'; --You can use GetDate() here if that what you mean by current date

答案 3 :(得分:0)

如果我理解您的问题,则需要在其中EmpId相同的表之间执行join,而不是应用过滤器。

SELECT 
  A.EmpID, B.NPINumber, B.NPIEndDate 
FROM 
  [Table A] A LEFT JOIN [Table B] B ON A.EmpID = B.EmpID 
WHERE 
  B.EmpID IS NULL 
  OR (NOT B.NPINumber IS NULL AND
  (B.[NPIEndDate] IS NULL OR B.[NPIEndDate] >= '2018/06/27'));

您可以使用此查询here