Sqlserver
 sql >> Database >  >> RDS >> Sqlserver

SQL Combina i dati di due diversi intervalli di date in un unico set di risultati

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;

Se li vuoi come una singola riga per ogni azienda, allora:

;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;