SQL Server - select union misma tabla

 
Vista:

select union misma tabla

Publicado por astros (1 intervención) el 13/12/2015 19:54:10
Hola tengo una duda que me esta dando dolores de cabeza a ver si alguien puede orientarme para solucionarla,
tengo una tabla donde almaceno los pagos (decimal), la fecha(date), y la forma de pago(string) en sql server 2008 ahora necesito sacar las estadisticas separadas por forma de pago y la verdad no he conseguido hacerlo.

he probado con union
1
select DATEPART(year,estadisticas.fecha)as AÑO,DATEpart(mm,estadisticas.fecha)as MES, SUM(convert(decimal(18,2),estadisticas.total))as efectivo FROM estadisticas WHERE estadisticas.pago LIKE '%EFECTIVO%'group by DATEPART(year,estadisticas.fecha),DATEpart(month,estadisticas.fecha)  UNION select DATEPART(year,estadisticas.fecha)as AÑO,DATEpart(mm,estadisticas.fecha)as MES, SUM(convert(decimal(18,2),estadisticas.total))as TOTAL FROM estadisticas  group by DATEPART(year,estadisticas.fecha),DATEpart(month,estadisticas.fecha)   ORDER by DATEPART(year,estadisticas.fecha),DATEpart(month,estadisticas.fecha)asc

esto devuelve solo la columna efectivo con resultados duplicados es decir un efectivo con el efectivo y otro apunte con el resultado de tarjeta pero en la columna efectivo.
agradeceria que alguien me diera un empujon hacia que camino seguir

Un saludo
astros
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder
sin imagen de perfil
Val: 86
Ha disminuido su posición en 2 puestos en SQL Server (en relación al último mes)
Gráfica de SQL Server

select union misma tabla

Publicado por Rafael (110 intervenciones) el 14/12/2015 08:54:02
A ver si te he entendido bien quieres en una columna lo que tienes en efectivo y el la otra el total sin importar de donde provenga...

Bueno si es eso prueba con esto que seguro te funciona:
1
2
3
4
5
6
7
8
9
SELECT DATEPART(YEAR, ESTADISTICAS.FECHA) AS AÑO
	 , DATEPART(MM, ESTADISTICAS.FECHA) AS MES
	 , SUM( CASE WHEN ESTADISTICAS.PAGO LIKE '%EFECTIVO%'
            THEN CONVERT(DECIMAL(18, 2), ESTADISTICAS.TOTAL)
            ELSE 0 END) AS EFECTIVO
	 , SUM(CONVERT(DECIMAL(18, 2), ESTADISTICAS.TOTAL)) AS TOTAL
FROM   ESTADISTICAS
GROUP  BY DATEPART(YEAR, ESTADISTICAS.FECHA)
	 , DATEPART(MM, ESTADISTICAS.FECHA)

Saludos

Pd. Si te sirve a ti esta informacion a mi me sirve un +1.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar