Tema: Agrupacion
Ver Mensaje Individual
  #4 (permalink)  
Antiguo 03/04/2014, 15:43
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: Agrupacion

al cliente lo que pida:

Código SQL:
Ver original
  1. DECLARE @temp TABLE
  2. (
  3. id INT,
  4. codigo VARCHAR(20),
  5. padreid INT
  6. )
  7.  
  8. INSERT INTO @temp VALUES (1 , '5' , NULL)
  9. INSERT INTO @temp VALUES (2 , '6-2' , 7)
  10. INSERT INTO @temp VALUES (3 ,'6-1' ,  7)
  11. INSERT INTO @temp VALUES (4 ,'5-1' , 1)
  12. INSERT INTO @temp VALUES (5 ,'5-1-1' ,  4)
  13. INSERT INTO @temp VALUES (6 ,'5-2' ,  1)
  14. INSERT INTO @temp VALUES (7 ,'6' ,  NULL)
  15.  
  16. DECLARE @temp2 TABLE
  17. (
  18. id INT,
  19. padreid INT,
  20. codigo VARCHAR(20),
  21. padre2 INT,
  22. id2 INT,
  23. codigo2 VARCHAR(20)
  24. )
  25.  
  26. INSERT INTO @temp2
  27. SELECT
  28. t1.id,t1.padreid,t1.codigo,t2.padreid AS padre2,t2.id AS id2,t2.codigo AS codigo2
  29. FROM @temp AS t1
  30. LEFT JOIN @temp AS t2 ON (t1.id=t2.padreid)
  31. WHERE t2.padreid IS NOT NULL
  32.  
  33.  
  34. SELECT id AS padre ,padreid AS id,codigo FROM (
  35. SELECT *,ROW_NUMBER() OVER(partition BY codigo ORDER BY id) AS rn FROM
  36. (
  37. SELECT id,padreid,codigo FROM @temp2
  38. UNION
  39. SELECT padre2,id2,codigo2 FROM @temp2
  40. ) AS query
  41. ) query2 WHERE rn=1

como son variables de tipo tabla se ejecuta todo el script de una sola vez :) y el resultado es:

padre id codigo
----------- ----------- --------------------
1 NULL 5
1 4 5-1
4 5 5-1-1
1 6 5-2
7 NULL 6
7 3 6-1
7 2 6-2
__________________
What does an execution plan say to t-sql query? Go f**k yourself, if you are not happy with me