Ver Mensaje Individual
  #11 (permalink)  
Antiguo 22/04/2016, 15:11
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: Validar campo anterior y decidir si se inserta un valor

Código SQL:
Ver original
  1. CREATE TABLE #temp
  2. (
  3. id INT,
  4. fecha datetime
  5. )
  6.  
  7. INSERT INTO #temp VALUES (900681,'01/04/2013')
  8. INSERT INTO #temp VALUES (900681,'01/05/2013')
  9. INSERT INTO #temp VALUES (900681,'01/06/2013')
  10. INSERT INTO #temp VALUES (900525,'04/03/2010')
  11. INSERT INTO #temp VALUES (900525,'01/02/2010')
  12. INSERT INTO #temp VALUES (900526,'01/03/2010')
  13. INSERT INTO #temp VALUES (900526,'01/04/2010')
  14. INSERT INTO #temp VALUES (900526,'01/05/2010')
  15. INSERT INTO #temp VALUES (900526,'01/06/2010')
  16.  
  17.  
  18. SELECT t1.rn, CASE WHEN t1.id=t2.id THEN 0 ELSE t1.id END AS test, t1.fecha FROM(
  19. SELECT ROW_NUMBER() OVER(partition BY id ORDER BY fecha) AS rn,* FROM #temp
  20. ) AS t1 LEFT JOIN
  21. (SELECT ROW_NUMBER() OVER(partition BY id ORDER BY fecha) AS rn,* FROM #temp) AS t2 ON (t1.id=t2.id AND (t1.rn)=t2.rn+1)

revisa este query, regresa un resultado parecido al que buscas :)


rn test fecha
1 900525 2010-01-02 00:00:00.000
2 0 2010-04-03 00:00:00.000
1 900526 2010-01-03 00:00:00.000
2 0 2010-01-04 00:00:00.000
3 0 2010-01-05 00:00:00.000
4 0 2010-01-06 00:00:00.000
1 900681 2013-01-04 00:00:00.000
2 0 2013-01-05 00:00:00.000
3 0 2013-01-06 00:00:00.000

Si te fijas el campo id esta repetido, y lo que hace el query es poner en los repetidos el valor de 0 y solo dejar 1(el de la fecha menor)
__________________
What does an execution plan say to t-sql query? Go f**k yourself, if you are not happy with me