sql >> Databáze >  >> RDS >> Sqlserver

SQL Kombinujte data ze dvou různých období do jedné sady výsledků

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;

Pokud je chcete jako jeden řádek pro každou společnost, pak:

;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. MySQL Group podle ID a nejnovějšího data a času

  2. Laravel SQLSTATE[22007]:Neplatný formát data a času:1292 Nesprávná hodnota data a času:'2019-03-10 02:00:39' pro sloupec 'updated_at' (letní čas?)

  3. Transakce uvnitř funkce plpgsql

  4. Jak rozdělit řetězec na SQL Server