创建表并从另一个表中获取数据

时间:2013-09-11 19:07:13

标签: sql sum

我有一张表费用类别:

CREATE TABLE [dbo].[CostCategory](
[ID_CostCategory] [int] NOT NULL,
[Name] [varchar](150) NOT NULL,
[Plan] [money] NOT NULL,
[Realization] [money] NULL,
)
go

我有另一张定义了费用的表:

CREATE TABLE [dbo].[Cost](
[ID_Cost] [int] NOT NULL,
[Name] [varchar](50) NULL,
[ID_CostCategory] [int] NULL,
[ID_Department] [int] NULL,
[ID_Project] [int] NULL,
[Value] [money] NULL,
)
go 

我想要做的是从Cost表(根据ID_CostCategory)求和并放入Cost Category表,Realization列。因此,每个ID_CostCategory都会自动计算成本表中的成本总和(按ID_CostCategory)。

如何修改“成本类别”表的脚本来实现它?可能它不是火箭科学,但我对SQL很陌生。


行。还有一件事我忘了补充...... 结构在某种程度上看起来:
成本>成本类别>部门>项目

现在我可以轻松地从成本表中获取数据并将其显示在“成本类别”表中。但成本表包括以下数据:

ID_Cost Name    ID_CostCategory ID_Department   ID_Project  Value
1   fv 001  1   1   1   100
2   fv 002  2   1   1   500
3   fv 003  2   2   1   300
4   fv 004  3   2   2   150
5   fv 005  3   3   2   30
6   fv 006  4   3   2   15

我还有表部门,其中包括列:ID_Department,Name,Plan,

所以现在,我想做的是对Cost表中的值进行求和(根据ID_CostCategory和ID_Department)并将其作为Realization列放入Department表中。因此,每个ID_Department都会自动显示成本表中的成本总和(根据ID_CostCategory和ID_Department)。

希望它很清楚(稍后将会使用表项目,但一旦我得到它,它将很容易)

2 个答案:

答案 0 :(得分:0)

您不需要将Realization列作为CostCategory表的一部分。相反,您将需要使用连接。

Select A.ID_CostCategory, A.Name, SUM(B.Value) As Realization from CostCategory A
JOIN Cost B ON A.ID_CostCategory = B.ID_CostCategory
Group By A.ID_CostCategory, A.Name

答案 1 :(得分:0)

试试这个

--create table without realization column
CREATE TABLE [dbo].[CostCategory](
[ID_CostCategory] [int] NOT NULL,
[Name] [varchar](150) NOT NULL,
[Plan] [money] NOT NULL
) go

CREATE TABLE [dbo].[Cost](
[ID_Cost] [int] NOT NULL,
[Name] [varchar](50) NULL,
[ID_CostCategory] [int] NULL,
[ID_Department] [int] NULL,
[ID_Project] [int] NULL,
[Value] [money] NULL,

) go 

创建UDF以计算成本列的总和:

CREATE FUNCTION [dbo].[CalculateRealization](@Id INT) 
RETURNS money
AS 
BEGIN
  DECLARE @cost money

  SELECT @cost = SUM(Value)
  FROM [dbo].[Cost]
  WHERE [ID_CostCategory] = @ID

  return @cost
END

现在更改您的CostCategory表以添加计算列:

ALTER TABLE [dbo].[CostCategory]
   ADD [Realization] AS dbo.CalculateRealization(ID_CostCategory);

现在您可以从Costcategory

中选择Realization
SELECT ID_CostCategory, Realization
FROM [dbo].[CostCategory]

回答下面的评论:

创建另一个UDF

CREATE FUNCTION [dbo].[CheckValue](@Id INT, @value Money) 
RETURNS INT
AS 
BEGIN
  DECLARE @flg INT
  SELECT @flg = CASE WHEN [Plan] >= @value THEN 1 ELSE 0 END
  FROM [dbo].[CostCategory]
  WHERE [ID_CostCategory] = @ID

  return @flg;
END

现在在成本表上添加约束:

ALTER TABLE ALTER TABLE [dbo].[Cost]
  ADD CONSTRAINT CHK_VAL_PLAN_COSTCATG
    CHECK(dbo.CheckValue(ID_CostCategory, Value) = 1)