0

我一直在尝试编写一个 SQL 查询来返回表中没有匹配值的所有行。

我有公司、工作、子工作、成本代码和成本类型(以及其他字段)。我需要返回所有具有“J”成本类型但没有“L”成本类型的行。

这可能用数据更好地解释:

Company  Job      Subjob  Costcode  Costtype
-------  -------- ------- --------- ----------
    1     1234             0132      J
    1     2345     01      9394      E
    1     2345     02      9233      L
    1     2345     02      9992      J
    1     2345     02      9992      L
    1     2345     03      1112      J
    1     3384             3928      J
    1     3384     03      3928      J
    1     3384     11      2838      L

所以我会期待以下内容:

Company  Job      Subjob  Costcode  Costtype
-------  -------- ------- --------- ----------
    1     1234             0132      J
    1     2345     03      1112      J
    1     3384             3928      J
    1     3384     03      3928      J

我知道我缺少一些简单的东西,但无法正确组合 JOIN、ON 和 WHERE 子句来使其工作。

4

3 回答 3

2

无需使用JOINs:

SELECT *
FROM YourTable A
WHERE EXISTS(SELECT 1 FROM YourTable
             WHERE Company = A.Company
             AND Job = A.Job
             AND Costtype = 'J')
AND NOT EXISTS(SELECT 1 FROM YourTable
               WHERE Company = A.Company
               AND Job = A.Job
               AND Costtype = 'L')
于 2013-08-27T21:28:12.547 回答
0

SELECT company, job, subjob, costcode FROM Table WHERE Company = A.Company AND Job = A.Job AND Costtype = 'J' 减去 SELECT company, job, subjob, costcode, FROM Table WHERE Company = A.Company AND Job = A .Job AND Costtype = 'L'

我希望这可以满足,除非您想在结果集中显示成本类型。

于 2013-08-27T22:12:40.490 回答
0
 SELECT * FROM COMPO T1
 WHERE Costtype='J'
 AND NOT EXISTS
(SELECT *  FROM COMPO T2 WHERE T1.Costcode=T2.Costcode AND Costtype ='L')

Company             Job     Subjob           Costcode          Costtype
1                   1,234       ?               0,132           J
1                   2,345       3               1,112           J
1                   3,384       ?               3,928           J
1                   3,384       3               3,928           J
于 2015-05-18T13:39:43.657 回答