SQL:如何将行拆分为多个计算行

时间:2014-01-27 19:42:54

标签: sql-server

我有3张这样的表:

ProductsTable
---------------------------------------------
ProductID   ProductName    ProductDescription
----------- -------------- ------------------
1           Name1          Description1
2           Name2          Description2

ValuesTable
--------------------------------
ProductID   Period         Value
----------- -------------- -----
1           2014Q1         100
1           2014Q2         110
1           2014Q3         105
2           2014Q1         80
2           2014Q2         85
2           2014Q3         90

MonthsTable
--------------------------------
Month       Period         Weeks
----------- -------------- -----
2014-Jan    2014Q1         4
2014-Feb    2014Q1         4
2014-Mar    2014Q1         5

我想要的是一个可以提供以下结果的查询:

ProductID     ProductName    Month      Value
1             Name1          2014-Jan   30.77
1             Name1          2014-Feb   30.77
1             Name1          2014-Mar   38.46

最后一列的值将由以下公式确定:

=(PV / SWP * MW)

,其中

  • PV:期间值
  • SWP:期间的周数总和
  • MW:本月的几周

提前致谢!

2 个答案:

答案 0 :(得分:1)

SELECT p.productID, p.productName, m.month, (v.value / swp * m.weeks)
FROM productsTable p, monthstable m, valuestable v,
     (SELECT m1.period, sum(m1.weeks) as swp 
      FROM monthsTable m1 
      GROUP BY m1.period) x
WHERE x.period = v.period AND p.productID = v.productID
      --and p.productID = 1 --if you want the results only for product 1

另一种方法是使用JOIN s(如果我没错):

SELECT p.productID, p.productName, month, (v.value / x.swp * m.weeks)
FROM productsTable p JOIN valuesTable v ON p.productID = v.productID
     JOIN (SELECT m1.period, sum(m1.weeks) as swp 
           FROM monthsTable m1 
           GROUP BY m1.period) x ON x.period = v.period
     JOIN monthsTable m ON x.period = m.period

您只需要通过正确的字段加入所有表格,并计算直接应用公式的最后一列。

答案 1 :(得分:0)

假设SQL Server 2005 +:

;WITH Months AS
(
    SELECT  *, 
            SUM(Weeks) OVER(PARTITION BY Period) QuarterWeeks
    FROM MonthsTable
)
SELECT  V.ProductID,
        P.ProductName,
        V.Value / M.QuarterWeeks * M.Weeks Value
FROM ValuesTable V
INNER JOIN ProductsTable P
    ON V.ProductID = P.ProductID
LEFT JOIN Months M
    ON V.Period = M.Period