如何在SQL Pivot查询中找出动态列的总和

时间:2019-02-27 05:34:25

标签: sql-server stored-procedures

我有一个存储过程,该过程接受日期和月份作为参数以产生每月出勤表。而且我必须找出特定员工的每月工作时间。

CREATE TABLE [dbo].[employee] (
  [EmpID] [int] IDENTITY(100,1) NOT NULL,
  [Name] [varchar](50) NULL,
  [DOB] [date] NULL,
  [DOJ] [date] NULL,
  [Email] [varchar](50) NULL,
  [Mob] [varchar](50) NULL,
  [Address] [varchar](max) NULL,
  CONSTRAINT [PK_tbl_employee] PRIMARY KEY CLUSTERED
  (
    [EmpID] ASC
  ) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO

CREATE TABLE [dbo].[Attendace] (
  [EmpID] [int] NOT NULL,
  [AttendaceDate] [date] NULL,
  [WorkHours] [int] NULL,
  [AtID] [int] IDENTITY(1,1) NOT NULL,
  CONSTRAINT [PK_Attendace] PRIMARY KEY CLUSTERED
  (
    [AtID] ASC
  ) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY]

GO

存储过程

ALTER procedure [dbo].[sps_AttendanceShowModified] @mon int, @year int
As begin DECLARE @cols  AS NVARCHAR(MAX)=''; DECLARE @query AS
NVARCHAR(MAX)='';

set @query =  'SELECT * from  (
     select  e.Name, a.WorkHours, DAY(a.AttendaceDate) AS d1
from Attendace a, employee e
where e.EmpID = a.EmpID and
MONTH(a.AttendaceDate) = ' + CONVERT(VARCHAR(12), @mon)+ ' AND
YEAR(a.AttendaceDate) = ' + CONVERT(VARCHAR(12), @year)+ ' ) src pivot 
(
    max(WorkHours) for d1 in ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],[21],[22],[23],[24],[25],[26],[27],[28],[29],[30])
) piv'

execute(@query) end

1 个答案:

答案 0 :(得分:2)

在这种情况下,您可以在选择列表中添加一列,如下所示。

sum(WorkHours) over(partition by name order by (select 1)) as Total

我已经创建了一个演示,您可以看一下。

Demo Online

您的最终查询应如下所示。

ALTER procedure [dbo].[sps_AttendanceShowModified] @mon int, @year int
As begin DECLARE @cols  AS NVARCHAR(MAX)=''; DECLARE @query AS
NVARCHAR(MAX)='';

set @query =  'SELECT name,Total,[1],[2],[3] from  (
     select  e.Name, a.WorkHours, DAY(a.AttendaceDate) AS d1, sum(WorkHours) over(partition by e.name order by (select 1)) as Total
from Attendace a, employee e
where e.EmpID = a.EmpID and
MONTH(a.AttendaceDate) = ' + CONVERT(VARCHAR(12), @mon)+ ' AND
YEAR(a.AttendaceDate) = ' + CONVERT(VARCHAR(12), @year)+ ' ) src pivot 
(
    max(WorkHours) for d1 in ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],[21],[22],[23],[24],[25],[26],[27],[28],[29],[30])
) piv'

execute(@query) end

注意:您需要在选择中包括其他列。