sql >> Base de Datos >  >> RDS >> Sqlserver

Cómo sumar el valor de las columnas dinámicas y agregarlo a otra columna dinámica

debe calcular el campo de columna total, es decir, no está en la lista de columnas dinámicas.

Datos

create table #CheckInCheckOut(Id int identity(1,1),UserId_Fk int,CountHours varchar(50),[Day] varchar(50))
INSERT INTO #CheckInCheckOut(UserId_Fk,CountHours,[Day]) VALUES
(1,'2','Sunday'),(1,'2','Monday'),(1,'2','Tuesday'),(1,'2','Wednesday'),(1,'2','Thursday'),(1,'2','Friday'),(1,'2','Saturday')
,(2,'3','Sunday'),(2,'3','Monday'),(2,'3','Tuesday'),(2,'3','Wednesday'),(2,'3','Thursday'),(2,'3','Friday'),(2,'3','Saturday')
,(3,'3','Sunday'),(3,'3','Monday'),(3,'3','Tuesday'),(3,'3','Wednesday'),(3,'3','Thursday'),(3,'3','Friday'),(3,'3','Saturday')


create table #Users(UserId int identity(1,1),FullName varchar(50))
INSERT #Users(FullName) values('Abdul'),('khan'),('Tariq')

Consulta para encontrar el total también:

select FullName
,[Sunday] = SUM([Sunday])
,[Monday] = SUM([Monday])
,[Tuesday] = SUM([Tuesday])
,[Wednesday] = SUM([Wednesday])
,[Thursday] = SUM([Thursday])
,[Friday] = SUM([Friday])
,[Saturday] = SUM([Saturday])
, Total= SUM([Sunday]+[Monday]+[Tuesday]+[Wednesday]+[Thursday]+[Friday]+[Saturday])
   from  
   (Select UserId_Fk,ISNULL(CAST(CountHours as decimal(18,2)),0)as CountHours,[Day] 
   from #CheckInCheckOut)
    as convertedtable
    inner join #Users
    on convertedtable.UserId_Fk=#Users.UserId
 PIVOT
(
 SUM(CountHours) 
 FOR Day
 IN([Sunday],[Monday],[Tuesday],[Wednesday],[Thursday],[Friday],[Saturday])
)
as PivotTable
GROUP BY FullName

Salida

Además, si desea un total horizontal y vertical, reemplace:

 --GROUP BY FullName
GROUP BY ROLLUP(FullName);

Para obtener más información, siga el enlace https://stackoverflow.com/a/17142530/1915855

DROP TABLE #CheckInCheckOut
DROP TABLE #Users