Maybe what I'm trying to explain is a bit convoluted, I explain:
I have a table with an imei field, id_factura, id_albaran, transaccion, estado(among others).
An imei can have a transacion
(compra or venta), and estado
(nuevo or usado).
In my query I only want it for 'nuevo' ones, in the table there are hundreds of records with imei but there can only be the same imei, estado='nuevo', transaccion='venta' with id_factura not null or/and id_albaran not null.
The objective of this query is to find out if the same imei, transacion=venta,estado=nuevo, has an id_factura record not null and another id_albaran record not null, so I want it to return a field if it has two records with a value of 1 or if it only has one record that return 0.
I give you an example of what I want the query to return, in my case I only want what is marked with red (sale).
I have tried this(but is wrong):
SELECT imei
FROM ventacompra
WHERE transacion = 'venta' AND estado='nuevo' AND id_albaran IS NOT NULL
AND imei IN (SELECT imei FROM ventacompra v WHERE transacion = 'venta' AND estado='nuevo' AND id_factura IS NOT NULL)
____EDIT FOR EXAMPLE____
transacion estado imei id_factura id_albaran has_factu_alba
venta nuevo 0001 01 NULL 1
venta nuevo 0001 NULL 01 1
compra nuevo 0002 01 NULL 0
With EXISTS
:
SELECT v.* FROM ventacompra v
WHERE v.transacion = 'venta' AND v.estado='nuevo' AND (v.id_factura IS NULL XOR v.id_albaran IS NULL)
AND EXISTS (
SELECT 1 FROM ventacompra
WHERE imei = v.imei AND transacion = v.transacion AND estado = v.estado
AND (id_factura IS NULL) = (v.id_factura IS NOT NULL)
AND (id_albaran IS NULL) = (v.id_albaran IS NOT NULL)
)
If one of the columns id_factura
and id_albaran
is always null
and the other not null
then you may omit the condition:
AND (v.id_factura IS NULL XOR v.id_albaran IS NULL)
See the demo.
Results:
| id_ventacompra | transacion | estado | imei | id_factura | id_albaran |
| -------------- | ---------- | ------ | --------------- | ---------- | ---------- |
| 492 | venta | nuevo | 352984109069491 | | 23 |
| 493 | venta | nuevo | 352984109069491 | 10 | |