Ver Mensaje Individual
  #4 (permalink)  
Antiguo 28/05/2015, 12:54
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: Consultar cliente actual con los máximos movimientos

Codigo SQL server

Código SQL:
Ver original
  1. CREATE TABLE #temp
  2. (
  3. id INT,
  4. cliente VARCHAR(10),
  5. fecha datetime
  6. )
  7.  
  8.  
  9. INSERT INTO #temp VALUES (1 ,'v1','2015-05-20')
  10. INSERT INTO #temp VALUES (2 ,'v1','2015-05-20')
  11. INSERT INTO #temp VALUES (3 ,'v1','2015-05-01')
  12. INSERT INTO #temp VALUES (4 ,'v1','2015-03-05')
  13. INSERT INTO #temp VALUES (5 ,'v2','2015-02-02')
  14. INSERT INTO #temp VALUES (6 ,'v3','2015-01-30')
  15. INSERT INTO #temp VALUES (7 ,'v1','2015-01-01')
  16.  
  17. SELECT calculo, id,cliente FROM(
  18. SELECT CASE WHEN t1.cliente<>t2.cliente THEN t2.fecha END AS calculo, t1.id AS id,t1.cliente AS cliente FROM #temp AS t1
  19. INNER JOIN #temp AS t2 ON (t1.id+1=t2.id)
  20. ) AS t3 WHERE calculo IS NOT NULL

Resultado:

calculo id cliente
2015-02-02 00:00:00.000 4 v1
2015-01-30 00:00:00.000 5 v2
2015-01-01 00:00:00.000 6 v3
__________________
What does an execution plan say to t-sql query? Go f**k yourself, if you are not happy with me