sql >> データベース >  >> RDS >> Sqlserver

2 つの異なる日付範囲のデータを 1 つの結果セットに結合する SQL

    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;
    

    会社ごとに 1 つの行として表示する場合は、次のようにします。

    ;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. T-SQLでのSQLServer正規表現

    2. PHPを使用して各登録ユーザーに独自のURLを与えるにはどうすればよいですか?

    3. 新しいMicrosoftAccess機能が登場します!

    4. MySQL:VARCHAR(255)の代わりにVARCHAR(20)を使用するのはなぜですか?