Ver Mensaje Individual
  #5 (permalink)  
Antiguo 31/03/2014, 14:26
Avatar de Libras
Libras
Colaborador
 
Fecha de Ingreso: agosto-2006
Ubicación: En la hermosa perla de occidente
Mensajes: 7.412
Antigüedad: 17 años, 8 meses
Puntos: 774
Respuesta: Update condicional

sencillo :P

Código SQL:
Ver original
  1. CREATE TABLE #temp
  2. (
  3. id INT,
  4. padre INT,
  5. state INT
  6. )
  7.  
  8.  
  9.  INSERT INTO #temp VALUES (19792             ,-1              ,1)
  10.  INSERT INTO #temp VALUES (19793,          19792             ,5)
  11.  INSERT INTO #temp VALUES (19794,          19792             ,7)
  12.  INSERT INTO #temp VALUES (19799,          19792             ,7)
  13.  
  14.  INSERT INTO #temp VALUES (19795             ,-1              ,1)
  15.  INSERT INTO #temp VALUES (19796,          19795             ,5)
  16.  INSERT INTO #temp VALUES (19797,          19795             ,7)
  17.  INSERT INTO #temp VALUES (19798,          19795             ,8)
  18.  
  19.  
  20.  SELECT t3.padre FROM(
  21.  SELECT COUNT(t1.id) AS total,t1.padre FROM #temp AS t1
  22.  LEFT JOIN #temp AS t2 ON (t1.id=t2.padre) WHERE t1.padre<>-1 GROUP BY t1.padre
  23.  ) t3
  24.  LEFT JOIN
  25.  ( SELECT COUNT(*) total,padre FROM #temp WHERE state IN (5,7) AND padre<>-1 GROUP BY padre) AS t4 ON (t3.padre=t4.padre)
  26.  WHERE t3.total=t4.total

aqui se obtiene el padre que tiene los hijos en estado 5 y 7 si te fijas en los datos de ejemplo el query solo regresa el id 19792 porque tiene 2 hijos en 5 y 7 y el 19795 tiene 3 hijos 2 en 5 y 7 y uno en 8 :P, ademas tomo en cuenta que los padres son los que tienen el -1
__________________
What does an execution plan say to t-sql query? Go f**k yourself, if you are not happy with me