Ver Mensaje Individual
  #4 (permalink)  
Antiguo 21/08/2013, 11:03
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: Select con 3 tablas

usando los valores que se necesitan(no use todos los campos de tus tablas) se puede lograr algo como esto:

Código SQL:
Ver original
  1. CREATE TABLE #temp
  2. (
  3. fecha datetime,
  4. linea INT,
  5. ptotal INT
  6. )
  7.  
  8. CREATE TABLE #temp2
  9. (
  10. cve INT,
  11. nombre VARCHAR(20)
  12. )
  13.  
  14. CREATE TABLE #temp3
  15. (
  16. id INT,
  17. [año] INT,
  18. mes INT,
  19. cuota INT
  20. )
  21.  
  22.  
  23. INSERT INTO #temp VALUES ('07/03/2013',444,15000)
  24. INSERT INTO #temp VALUES ('07/23/2013',321,12500)
  25. INSERT INTO #temp VALUES ('07/24/2013',524,2400)
  26. INSERT INTO #temp VALUES ('07/03/2012',444,45000)
  27. INSERT INTO #temp VALUES ('07/04/2012',321,2500)
  28. INSERT INTO #temp VALUES ('07/24/2012',524,600)
  29.  
  30.  
  31. INSERT INTO #temp2 VALUES (444,'Kimberly')
  32. INSERT INTO #temp2 VALUES (321,'Diageo')
  33. INSERT INTO #temp2 VALUES (524,'choice')
  34. INSERT INTO #temp2 VALUES (525,'Libras')
  35.  
  36.  
  37. INSERT INTO #temp3 VALUES (321,2013,7,20000)
  38. INSERT INTO #temp3 VALUES (444,2013,5,3000)
  39. INSERT INTO #temp3 VALUES (444,2013,6,25000)
  40. INSERT INTO #temp3 VALUES (321,2013,5,500)
  41. INSERT INTO #temp3 VALUES (524,2013,7,26000)
  42. INSERT INTO #temp3 VALUES (524,2013,7,30000)
  43.  
  44. --------obtenemos la suma por los años(2013 y 2012 y por el mes 7, almacenamos este resultado en una tabla temporal #temp4)
  45.  
  46. SELECT año,linea,SUM(total) total INTO #temp4 FROM(
  47. SELECT datepart(yyyy,fecha) AS año,linea,SUM(ptotal) total FROM #temp WHERE datepart(mm,fecha)=7 GROUP BY
  48. datepart(yyyy,fecha),linea
  49. ) AS tabla GROUP BY año,linea
  50.  
  51.  
  52. SELECT nombre,SUM(isnull(cuota,0)) cuota,isnull(t4.[2012],0) AS [2012],isnull(t4.[2013],0) AS [2013] FROM(
  53. SELECT * FROM #temp3 AS t2
  54. WHERE t2.mes=7 AND t2.año=2013
  55. ) t1
  56. RIGHT JOIN #temp2 AS t3 ON (t1.id=t3.cve)
  57. LEFT JOIN (
  58. SELECT linea,[2012],[2013]
  59. FROM
  60. (
  61. SELECT año,total,linea FROM #temp4) AS sourcetable
  62. pivot(SUM(total) FOR año IN ([2012],[2013])
  63. ) AS pivottable
  64. ) AS t4 ON (t3.cve=t4.linea)
  65. GROUP BY año,mes,nombre,[2012],[2013]

saludos!
__________________
What does an execution plan say to t-sql query? Go f**k yourself, if you are not happy with me