0

我知道这会很容易,但我不记得该怎么做,我有查询请参阅下面我想添加一个名为 Total Capacity 的新列,这是我的 datediff 结果 * 我的 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

4 回答 4

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
于 2013-02-25T13:51:54.257 回答
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
于 2013-02-25T13:47:17.380 回答
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
于 2013-02-25T13:47:23.660 回答
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
于 2013-02-25T13:50:52.173 回答