Mysql - Get all records where there is an equal value in one field and in turn have a non null value in other fields

Sylar :

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).

enter image description here

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
forpas :

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         |            |

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=402232&siteId=1