SQL将来自两个不同日期范围的数据合并为一个结果集

时间:2012-03-07 15:35:34

标签: sql-server-2008

使用SqlServer 2008,我有一个临时表(#tmpAllSales),可以捕获一年的所有销售额。我想创建一个SELECT语句,其中包含当年的销售额以及上一季度的销售额。

像这样的事情(@StartDate& @EndDate定义为季度的开始/结束):

--QTD Sales By Company
SELECT
    Company,
    SUM(Call) as TotalCallsQTD,
    SUM(Call) - SUM(SoldCall) as FreeCallsQTD,
    SUM(SalableCall) as SalesRelatedCallsQTD,
    SUM(SoldCall) as SoldCallsQTD
FROM
    #tmpAllSales
WHERE
    CalledOn between @StartDate and @EndDate
GROUP BY
    Company

--COMBINED WITH BASED ON Company

--YTD Sales By Company
SELECT
    Company,
    SUM(Call) as TotalCallsYTD,
    SUM(Call) - SUM(SoldCall) as FreeCallsYTD,
    SUM(SalableCall) as SalesRelatedCallsYTD,
    SUM(SoldCall) as SoldCallsYTD
FROM
    #tmpAllSales
GROUP BY
    Company
ORDER BY
    Company

每个单独的查询都会给出我想要的结果,但我不知道如何组合成一个结果集。

修改

我在原帖中没有说清楚我希望每个公司获得一行的所有结果。我在Excel宏中使用它,所以如果所有信息都在一行上就会很棒。

1 个答案:

答案 0 :(得分:1)

SELECT
    Period = 'QTD',
    Company,
    SUM(Call) as TotalCallsQTD,
    SUM(Call) - SUM(SoldCall) as FreeCallsQTD,
    SUM(SalableCall) as SalesRelatedCallsQTD,
    SUM(SoldCall) as SoldCallsQTD
FROM
    #tmpAllSales
WHERE
    CalledOn between @StartDate and @EndDate
GROUP BY
    Company
UNION ALL
SELECT
    Period = 'YTD',
    Company,
    SUM(Call) as TotalCallsYTD,
    SUM(Call) - SUM(SoldCall) as FreeCallsYTD,
    SUM(SalableCall) as SalesRelatedCallsYTD,
    SUM(SoldCall) as SoldCallsYTD
FROM
    #tmpAllSales
GROUP BY
    Company
ORDER BY
    Period, Company;

如果您希望将它们作为每个公司的单行,那么:

;WITH q AS
(
    SELECT
        Company,
        SUM(Call) as TotalCallsQTD,
        SUM(Call) - SUM(SoldCall) as FreeCallsQTD,
        SUM(SalableCall) as SalesRelatedCallsQTD,
        SUM(SoldCall) as SoldCallsQTD
    FROM
        #tmpAllSales
    WHERE
        CalledOn between @StartDate and @EndDate
    GROUP BY
        Company
), y AS 
(
    SELECT
        Company,
        SUM(Call) as TotalCallsYTD,
        SUM(Call) - SUM(SoldCall) as FreeCallsYTD,
        SUM(SalableCall) as SalesRelatedCallsYTD,
        SUM(SoldCall) as SoldCallsYTD
    FROM
        #tmpAllSales
    GROUP BY
        Company
)
SELECT q.Company, qTotalCallsYTD = q.TotalCallsYTD, etc...,
    yTotalCallsYTD = y.TotalCallsYTD, etc...
FROM q INNER JOIN y
ON q.Company = y.Company
ORDER BY q.Company;