创建一个新的计算列

时间:2013-02-25 13:44:19

标签: sql sql-server tsql

我知道这很容易但我不记得怎么做了,我有查询在下面我要添加一个名为Total Capacity的新列,这是我的约会结果*我的Capcity。但对于我的生活,我无法理解。你能帮忙吗?

SELECT
  Capacity.StartDate
  ,Capacity.EndDate, DATEDIFF(d,Capacity.StartDate
  ,Capacity.EndDate)+1 AS DaysOpen
  ,Capacity.Capacity
  ,Capacity.Site_Skey
FROM
  Capacity

结果

  StartDate   EndDate       DaysOpen   Capacity TotalCapacity
  01/05/2010  30/09/2010    153        46       7038

4 个答案:

答案 0 :(得分:3)

您可以轻松地将这两列添加到您的表中 - 作为计算的,持久的列。然后你可以让它们易于选择 - 它们是你表中的新专栏,你可以选择其他列 - 如果你需要,你甚至可以在它们上面添加一个索引!

ALTER TABLE [dbo].[Capacity]
    ADD DaysOpen AS DATEDIFF(d, StartDate, EndDate) PERSISTED

ALTER TABLE [dbo].[Capacity]
    ADD TotalCapacity AS DATEDIFF(d, StartDate, EndDate) * [Capacity] PERSISTED

现在您可以发出:

SELECT
    StartDate, EndDate,
    DaysOpen,
    Capacity,
    TotalCapacity
FROM
    Capacity

更新:如果您想使用DATEDIFF+1方法,请使用以下列规范:

ALTER TABLE [dbo].[Capacity]
    ADD DaysOpen AS (DATEDIFF(d, StartDate, EndDate) + 1) PERSISTED

ALTER TABLE [dbo].[Capacity]
    ADD TotalCapacity AS (DATEDIFF(d, StartDate, EndDate) + 1) * [Capacity] PERSISTED

答案 1 :(得分:2)

SELECT
  Capacity.StartDate
  ,Capacity.EndDate
  ,DATEDIFF(d,Capacity.StartDate ,Capacity.EndDate)+1 AS DaysOpen
  ,Capacity.Capacity
  ,(DATEDIFF(d,Capacity.StartDate ,Capacity.EndDate)+1) * Capacity.Capcity as TotalCapacity
  ,Capacity.Site_Skey
FROM
  Capacity

答案 2 :(得分:2)

这样的东西?

SELECT
  Capacity.StartDate
  ,Capacity.EndDate
  ,DATEDIFF(d, Capacity.StartDate, Capacity.EndDate) + 1 AS DaysOpen
  ,Capacity.Capacity
  ,(DATEDIFF(d, Capacity.StartDate, Capacity.EndDate) + 1) * Capacity.Capacity AS TotalCapacity
FROM
  Capacity

答案 3 :(得分:1)

SELECT
  Capacity.StartDate
  ,Capacity.EndDate
  ,DATEDIFF(d,Capacity.StartDate
  ,Capacity.EndDate)+1 AS DaysOpen
  ,Capacity.Capacity
  ,Capacity.Site_Skey
  ,(DATEDIFF(d,Capacity.StartDate
  ,Capacity.EndDate)+1 ) * Capacity.Capacity
FROM
  Capacity