sql >> Database >  >> RDS >> Sqlserver

SQL Combineer gegevens uit twee verschillende datumbereiken in één resultaatset

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;

Als u ze als een enkele rij voor elk bedrijf wilt, dan:

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



  1. AVG + Innerlijke samenvoeging

  2. hoe voer ik een functie van TOAD voor Oracle uit en bind ik het resultaat aan een gegevensraster?

  3. Grote resultaatsets streamen met MySQL 4.1.x + Connector/J

  4. SQLAlchemy JSON als blob/tekst