Ver Mensaje Individual
  #8 (permalink)  
Antiguo 24/10/2014, 16:48
Avatar de leandro_reyes
leandro_reyes
 
Fecha de Ingreso: octubre-2013
Mensajes: 7
Antigüedad: 10 años, 7 meses
Puntos: 0
Mensaje Respuesta: Select comparando dos registros de la misma tabla SQL SERVER

Cita:
Iniciado por Libras Ver Mensaje
siguiendo tu logica:


Código SQL:
Ver original
  1. CREATE TABLE #temp
  2. (STATUS VARCHAR(20),
  3.  cuota INT,
  4.  factura INT)
  5.  
  6. INSERT INTO #temp VALUES ('C', 1, 345 )
  7. INSERT INTO #temp VALUES ('C', 2, 345 )
  8. INSERT INTO #temp VALUES ('O', 3, 345 )
  9. INSERT INTO #temp VALUES ('O', 4, 345 )
  10.  
  11. INSERT INTO #temp VALUES ('C', 1, 346 )
  12. INSERT INTO #temp VALUES ('C', 2, 346 )
  13. INSERT INTO #temp VALUES ('O', 3, 346 )
  14.  
  15. INSERT INTO #temp VALUES ('C', 1, 347 )
  16. INSERT INTO #temp VALUES ('C', 2, 347 )
  17. INSERT INTO #temp VALUES ('O', 3, 347 )
  18. INSERT INTO #temp VALUES ('O', 4, 347 )
  19. INSERT INTO #temp VALUES ('O', 5, 347)
  20.  
  21.  
  22.  
  23.  
  24. SELECT CASE WHEN test=3 THEN factura END AS resultado FROM
  25. (
  26. SELECT SUM(cuenta) AS test, factura FROM(
  27. SELECT
  28. CASE WHEN STATUS='o' THEN 1 ELSE 2 END AS cuenta, t1.*
  29.  FROM #temp AS t1
  30. LEFT JOIN(
  31. SELECT MAX(cuota) AS maximo, factura FROM #temp GROUP BY factura
  32. UNION
  33. SELECT MAX(cuota)-1 AS maximo, factura FROM #temp GROUP BY factura
  34. ) AS t2 ON (t1.cuota=t2.maximo AND t1.factura=t2.factura)
  35. WHERE t2.maximo IS NOT NULL
  36. ) AS t3 GROUP BY factura
  37. ) AS t4

saludos!



Lo probaré y adaptaré a mi necesidad. Gracias hay les aviso como me queda