从现有表创建新的SQL Server表

时间:2019-04-11 19:27:17

标签: sql sql-server group-by migrate

我的工作是删除月列,然后在列字段上重新创建该表分组,并对小时列求和,从而更新数据库表。

这是我的指示:“创建一个不带“月”列的新PS_StaffHours表。通过将(PSScnID / PSEmpID / Prd / WBSID / RatePrd)分组,将现有的PS_StaffHours数据迁移到新表中。”

现在这是我编写的表,必须在没有“月”列和“小时”列求和的情况下重新创建:

CREATE TABLE [dbo].[PS_StaffHours]
(
    [PSScnID] [int] NOT NULL,
    [PSEmpID] [int] NOT NULL,
    [Prd] [int] NOT NULL,
    [WBSID] [int] NOT NULL,
    [RatePrd] [int] NOT NULL,
    [Month] [date] NOT NULL,
    [Hours] [decimal](16, 8) NOT NULL,

   CONSTRAINT [PK_PS_StaffHours] 
       PRIMARY KEY CLUSTERED ([PSScnID] ASC, [PSEmpID] ASC, [Prd] ASC,
                              [WBSID] ASC, [RatePrd] ASC, [Month] 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 TABLE [dbo].[PS_StaffHours] WITH CHECK 
    ADD CONSTRAINT [FK_PS_StaffHours_PS_Scenarios] 
        FOREIGN KEY([PSScnID]) REFERENCES [dbo].[PS_Scenarios] ([PSScnID])
GO

ALTER TABLE [dbo].[PS_StaffHours] CHECK CONSTRAINT [FK_PS_StaffHours_PS_Scenarios]
GO

ALTER TABLE [dbo].[PS_StaffHours] WITH CHECK 
    ADD CONSTRAINT [FK_PS_StaffHours_PS_Staff] 
        FOREIGN KEY([PSScnID], [PSEmpID]) REFERENCES [dbo].[PS_Staff] ([PSScnID], [PSEmpID])
GO

ALTER TABLE [dbo].[PS_StaffHours] CHECK CONSTRAINT [FK_PS_StaffHours_PS_Staff]
GO

ALTER TABLE [dbo].[PS_StaffHours] WITH CHECK 
    ADD CONSTRAINT [FK_PS_StaffHours_PS_WBS] 
        FOREIGN KEY([PSScnID], [WBSID]) REFERENCES [dbo].[PS_WBS] ([PSScnID], [WBSID])
GO

ALTER TABLE [dbo].[PS_StaffHours] CHECK CONSTRAINT [FK_PS_StaffHours_PS_WBS]
GO

ALTER TABLE [dbo].[PS_StaffHours] WITH CHECK 
    ADD CONSTRAINT [CK_PS_StaffHours] CHECK ((DATEPART(day, [Month]) = (1)))
GO

ALTER TABLE [dbo].[PS_StaffHours] CHECK CONSTRAINT [CK_PS_StaffHours]
GO

EXEC sys.sp_addextendedproperty 
         @name = N'MS_Description', 
         @value = N'Restricts Month field to the 1st of every month.' , 
         @level0type = N'SCHEMA', @level0name = N'dbo',  
         @level1type = N'TABLE', @level1name = N'PS_StaffHours',  
         @level2type = N'CONSTRAINT', @level2name = N'CK_PS_StaffHours'
GO

首先,要创建新表,我想要做的就是重命名脚本CREATE部分中的表名,然后删除CREATE语句中Month列的所有引用。我对CREATE脚本的想法正确吗?

现在,这是我将用于填充不带“月”字段的表的脚本,但是我不确定分组是否正确,因为我遇到了错误,因为我不是{{1}在“小时”列上,其余的。另外,我不确定如何grouping处理查询中的时间。

我的代码:

summing

1 个答案:

答案 0 :(得分:1)

您的第一个假设是正确的。 要按列分组并汇总小时数,请尝试以下方法:

SELECT c.PSScnID, c.PSEmpID, c.Prd, c.WBSID, c.RatePrd, SUM(c.Hours) AS Hours
INTO dbo.NewPS_StaffHours 
FROM PS_StaffHours AS c  
GROUP BY c.PSScnID, c.PSEmpID, c.Prd, c.WBSID, c.RatePrd  
GO

听起来像在运行选择之前将要创建表。 因此,摆脱INTO dbo.NewPS_StaffHours。运行创建表语句,然后和INSERT INTO newTable VALUES... SELECT