显示一个表中的记录,该表不是多列中的另一个表

时间:2017-11-30 04:12:31

标签: sql sql-server tsql

我正在使用SQL Server 2012 Express进行以下查询。

表-A

CLIENT              TYPEOFWORK               ACTIVITY
-----------------------------------------------------
CLIENT A            WORK A                   ACTIVITY A
CLIENT A            WORK B                   ACTIVITY B
CLIENT A            WORK C                   ACTIVITY C
CLIENT A            WORK C                   NULL

表-B

CLIENT               TYPEOFWORK                 STATUS
--------------------------------------------------------
CLIENT A             WORK C                     COMPLETED

我想显示来自Table_A Table_B clienttypeofwork不在CLIENT TYPEOFWORK ACTIVITY ------------------------------------------------------ CLIENT A WORK A ACTIVITY A CLIENT A WORK B ACTIVITY B 的记录。

我需要关注输出。

NOT IN

我尝试使用Current URL URL generate by LINK localhost/products (here index is the method) localhost/users/add localhost/products/add localhost/products/users/add localhost/products/edit/1 localhost/products/edit/users/add ,但它仅适用于一列

提前谢谢

6 个答案:

答案 0 :(得分:0)

尝试:使用NOT EXISTS

以下是轻松的完整方案:

CREATE TABLE #table_a(CLIENT VARCHAR(50), TYPEOFWORK VARCHAR(50), ACTIVITY VARCHAR(50))
INSERT INTO #table_a VALUES
('CLIENT A', 'WORK A', 'ACTIVITY A'),
('CLIENT A', 'WORK B', 'ACTIVITY B'),
('CLIENT A', 'WORK C', 'ACTIVITY C'),
('CLIENT A', 'WORK C', NULL)

CREATE TABLE #table_b(CLIENT VARCHAR(50), TYPEOFWORK VARCHAR(50), STATUS VARCHAR(50))
INSERT INTO #table_b values
('CLIENT A', 'WORK C', 'COMPLETED')

SELECT 
    a.client,
    a.typeofwork,
    a.activity
FROM #table_a a
WHERE NOT EXISTS(SELECT 1 FROM #table_b b 
                 WHERE a.client = b.client AND a.typeofwork = b.typeofwork)

<强>输出:

client      typeofwork  activity
----------------------------------
CLIENT A    WORK A      ACTIVITY A
CLIENT A    WORK B      ACTIVITY B

答案 1 :(得分:0)

我假设您希望客户端列匹配并且typeofwork不相同,这是正确的吗?如果是这样,您可以在列条件上保持联接:

SELECT A.CLIENT, A.TYPEOFWORK, A.STATUS
FROM TABLE_A A
LEFT JOIN TABLE_B B ON B.CLIENT = A.CLIENT AND 
A.TYPEOFWORK <> B.TYPEOFWORK
WHERE B.CLIENT IS NULL

答案 2 :(得分:0)

SELECT A.CLIENT, A.TYPEOFWORK, A.ACTIVITY
FROM TABLE_A A
LEFT JOIN TABLE_B B 
ON A.CLIENT = B.CLIENT 
AND A.TYPEOFWORK = B.TYPEOFWORK
WHERE B.CLIENT IS NULL 
OR B.TYPEOFWORK IS NULL;

答案 3 :(得分:0)

尝试使用以下查询:

SELECT * FROM Table_A
WHERE 
  NOT EXISTS (
    SELECT * FROM Table_B WHERE CLIENT = Table_A.CLIENT AND TYPEOFWORK = Table_A.TYPEOFWORK
  )

希望它符合您的目的。请参阅演示here

答案 4 :(得分:-1)

试试这个:

Select * from Table_A 
where Client NOT IN (Select Client from Table_B)
and TypeOFWork NOT IN (Select TypeOfWork from Table_B)

答案 5 :(得分:-1)

尝试以下方法:

SELECT A.*
FROM TABLE_A A
LEFT JOIN TABLE_B B ON B.CLIENT = A.CLIENT AND A.TYPEOFWORK = B.TYPEOFWORK
WHERE B.[STATUS] IS NULL

感谢。