从两个查询中为每行增加一列

Incrementing a column for each rows from two queries

我有两个查询,分别给出购买的工作单位数和客户消耗的工作单位数。

我正在开发 SQL Server 2014

WUBought 查询 returns 类似于此示例:

Customer    Year    Month   UnitBought
Cust1       2015    6       50
Cust2       2014    7       100
Cust1       2013    10      30
Cust3       2015    2       40

另一个查询returns客户端消费的数量:

Customer    Year    Month   UnitConsumed
Cust1       2015    2       6
Cust1       2015    5       20
Cust2       2015    3       8
Cust1       2015    4       3
Cust3       2015    2       10

我基本上想做的是,每个月购买的东西减去消费的东西。这是我想要的 Cust1 前六个月结果的示例:

Customer    Year    Month   Remaining
Cust1       2015    1       30
Cust1       2015    2       24
Cust2       2015    3       24
Cust1       2015    4       21
Cust3       2015    5       1
Cust3       2015    6       51

returns WU 使用 UNION ALL 从每个月列出的 table 中购买的查询,即使没有值也可以获取每个月:

SELECT Customer, [Year], [Month], SUM(UOBought) AS UORest
    FROM WU_Bought
    GROUP BY [Customer], [PurchaseDate]
UNION ALL
SELECT '' AS Customer, [Year], [Month], '' AS UORest
    FROM  Months
    GROUP BY [Year], [Month]

这是每月对每个购买的单位求和的查询,使用相同的联合语句:

SELECT Customer, [Year], [Month], SUM(TotalConsumed) * -1 AS UORest
    FROM WUConsumed
    GROUP BY Customer, Year, Month
UNION ALL
SELECT '' AS Customer, [Year], [Month], '' AS UORest
    FROM EveryMonths
    GROUP BY Year, Month

现在我想我必须调整第一个,强制它保持以前的总和,但我不确定我该怎么做。

这对你有用吗?

SELECT b.customer_id, b.year, b.month, SUM(b.units_bought) AS units_bought, ISNULL(c.units_consumed,0) AS units_consumed, SUM(b.units_bought) - ISNULL(c.units_consumed,0) AS units_remaining
    FROM Bought b
    LEFT JOIN Consumed c
        ON b.customer_id = c.customer_id AND b.year = c.year AND b.month = c.month
GROUP BY b.customer_id, b.year, b.month

好的,我成功了。

我所做的实际上是 "simple",使用 SQL 服务器功能,自 2012 年起可用: 行无限前导

Here is a pretty clear article 关于此功能。

我创建了另一个视图,使用名为 "WU_Closing_View" 的 UNION ALL 子句对有关消耗和购买单位的查询结果进行分组,然后在其中使用了 ROWS UNBOUNDED PRECEDING :

SELECT Customer, Year, Month, SUM(Closing) OVER(PARTITION BY Customer ORDER BY Year, Month ROWS UNBOUNDED PRECEDING) AS Closing
    FROM WU_Closing_View
    GROUP BY Customer, Year, Month, Closing
UNION ALL
SELECT     '' AS Customer, Year, Month, '' AS Sum_bought
    FROM         Months
    GROUP BY Year, Month
    ORDER BY Customer, Year, Month

请注意,我使用了 PARTITION BY,以便按客户求和。因为我想在 SSRS 矩阵中显示每个月,所以我添加了一个 "UNION ALL" 指向一个 table,对于一个空客户端,从 2010 年到 2017 年,它上面有每年和每月。但它是可选的如果你不需要每个月的进化。

可能有更简单的方法,但这是我目前找到的方法。