需要使用T-SQL添加计算字段

时间:2013-06-07 21:30:11

标签: tsql sql-server-2012-express

我有一个查询,我想添加一个计算字段。我需要添加2013年的预计销售额。计算结果将是当前的月数除以总年度的销售时间12.我有一个FiscalMonthNum的字段尚未在查询中。有人可以告诉我如何添加我需要的字段吗?

SELECT
    a.Vendor,
    vn.ACNAME AS Vendor_Name,
    a.FiscalYear,
    a.QtySold,
    a.ExtCost
FROM
    dbo.S2K_VEND vn
    INNER JOIN
(SELECT
    sd.IFPRVN AS Vendor,
    fc.FiscalYear,
    SUM(sd.SBQSHP) AS QtySold,
    SUM(sd.SBEPRC) AS ExtCost
FROM
    dbo.SalesData sd
    LEFT OUTER JOIN dbo.FiscalCalendar fc ON fc.FiscalDate = sd.SBINDT
WHERE
    sd.SBTYPE = 'O'
AND
    sd.SBINDT > '2011-12-31'
AND
    sd.SBCLS NOT IN ('1500')
GROUP BY
    sd.IFPRVN,
    fc.FiscalYear
)a
ON vn.ACVEND = a.Vendor
GROUP BY
    a.Vendor,
    vn.ACNAME,
    a.FiscalYear,
    a.QtySold,
    a.ExtCost

1 个答案:

答案 0 :(得分:0)

以下是否可以解决问题?将销售额除以最大月数,再乘以12?

SELECT
    a.Vendor,
    vn.ACNAME AS Vendor_Name,
    a.FiscalYear,
    a.QtySold,
    a.ExtCost,
    a.PredictedQtySold,
    a.PredictedExtCost
FROM
    dbo.S2K_VEND vn
    INNER JOIN
(SELECT
    sd.IFPRVN AS Vendor,
    fc.FiscalYear,
    12 * (SUM(sd.SBQSHP)/MAX(FiscalMonthNumber)) AS PredictedQtySold,
    12 * (SUM(sd.SBEPRC)/MAX(FiscalMonthNumber)) AS PredictedExtCost,
    SUM(sd.SBQSHP) AS QtySold,
    SUM(sd.SBEPRC) AS ExtCost
FROM
    dbo.SalesData sd
    LEFT OUTER JOIN dbo.FiscalCalendar fc ON fc.FiscalDate = sd.SBINDT
WHERE
    sd.SBTYPE = 'O'
AND
    sd.SBINDT > '2011-12-31'
AND
    sd.SBCLS NOT IN ('1500')
GROUP BY
    sd.IFPRVN,
    fc.FiscalYear
)a
ON vn.ACVEND = a.Vendor
GROUP BY
    a.Vendor,
    vn.ACNAME,
    a.FiscalYear,
    a.QtySold,
    a.ExtCost
;