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

Query SQL - Crescita delle vendite anno per anno

Prova questa query:

SELECT t1.tenant, t1.YEAR, t1.SALES,
    CASE WHEN t2.YEAR IS NOT NULL THEN
        FORMAT(
            CONVERT(DECIMAL(10, 2), (t1.SALES - t2.SALES)) /
            CONVERT(DECIMAL(10, 2), t2.SALES), 'p')
    ELSE NULL END AS "YEARLY GROWTH"
FROM
(
    SELECT tenant, YEAR(date) AS YEAR, SUM(sales) AS SALES
    FROM tenantSales
    GROUP BY tenant, YEAR(date)
) t1
LEFT JOIN
(
    SELECT tenant, YEAR(date) AS YEAR, SUM(sales) AS SALES
    FROM tenantSales
    GROUP BY tenant, YEAR(date)
) t2
ON t1.tenant = t2.tenant AND t2.YEAR = t1.YEAR - 1

Fare clic sul collegamento seguente per una demo funzionante:

SQLFiddle

Aggiornamento in ritardo:

Puoi anche provare lo stesso approccio usando Common Table Expressions. Ecco come sarebbe la query precedente utilizzando questo approccio:

WITH cte AS(SELECT tenant, YEAR(date) AS YEAR, SUM(sales) AS SALES
            FROM tenantSales
            GROUP BY tenant, YEAR(date))
SELECT c1.*, CONVERT(varchar,
                 CONVERT(DECIMAL(10,2),
                     CONVERT(DECIMAL(10, 2), (c1.SALES - c2.SALES)) /
                     CONVERT(DECIMAL(10, 2), c2.SALES))) + '%' AS "YEARLY GROWTH"
FROM cte c1
LEFT JOIN cte c2 ON c1.tenant = c2.tenant AND c2.YEAR = c1.YEAR - 1

Ed ecco un altro Fiddle dove puoi provarlo:

SQLFiddle