Question

I've been trying to write a SQL query to return all rows in a table without a matching value.

I have company, job, subjob, costcode, and costtype (among other fields). I need to return all rows which have a 'J' costtype, but no 'L' costtype.

This is probably better explained with data:

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

So I would expect the following:

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

I know it's something simple I'm missing, but cannot get the right combination of JOIN, ON, and WHERE clauses to make it work.

Était-ce utile?

La solution

No need to use 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')

Autres conseils

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

I hope this satisfies,unless you want to display cost type in your result set.

 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
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top