0

El ejercicios trata de mostrar el monto total comprado por año y país también q se especifique el porcentaje acorde al monto total del año y la diferencia con el año anterior. Ejm1:

AÑO       PAIS            Monto       %       Diferencia
1996      Argentina       $50000       50%    $50000
1996      Brazil          $40000       40%    $40000    #=>Total al año=100000
1996      Colombia        $10000       10%    $10000

1997      Peru            $10          10%    $10
1997      Brazil          $20          20%    $39980    #=>Total al año = 100
1997      Venezuela       $60          60%    $60
1997      Argentina       $10          10%    $49990

Mi avance hasta ahora es este no se si estará bien por que tarda en ejecutar:

select *,
           isnull((select distinct
                                   sum(os.Subtotal + o.Freight)
                                       over ( partition by year(o.OrderDate),o.ShipCountry
                                           order by year(o.OrderDate),o.ShipCountry
                                           )         Monto
                   from [Order Subtotals] OS
                            join Orders O
                                 on OS.OrderID = O.OrderID
                   where year(o.OrderDate) = TDA1.Año - 1
                     AND o.ShipCountry = TDA1.Pais), 0)-Monto Diferencia
    from (select distinct year(o.OrderDate)                                  Año,
                          o.ShipCountry                                      Pais,
                          sum(os.Subtotal + o.Freight)
                              over ( partition by year(o.OrderDate),o.ShipCountry
                                  order by year(o.OrderDate),o.ShipCountry
                                  )                                          Monto,
                          ((sum(os.Subtotal + o.Freight)
                                over ( partition by year(o.OrderDate),o.ShipCountry
                                    order by year(o.OrderDate),o.ShipCountry
                                    )) * 100) / (select Acumulado
                                                 from (select distinct year(o.OrderDate)                          Año,
                                                                       o.ShipCountry                              Pais,
                                                                       sum(os.Subtotal + o.Freight)
                                                                           over (partition by year(o.OrderDate) ) Acumulado
                                                       from [Order Subtotals] OS
                                                                join Orders O
                                                                     on OS.OrderID = O.OrderID) TD1
                                                 where Año = year(o.OrderDate)
                                                   and Pais = o.ShipCountry) Porcentaje
          from [Order Subtotals] OS
                   join Orders O
                        on OS.OrderID = O.OrderID
         ) TDA1;

Muchas gracias de antemano

3
  • Puedes dar más información? La estructura de la base de datos por ejemplo
    – Jose
    el 30 oct. 2019 a las 0:17
  • Es la base de datos northwind
    – Christian
    el 30 oct. 2019 a las 11:07
  • Versión de tu instancia de SQL Server? O el resultado de ejecutar SELECT @@VERSION el 30 oct. 2019 a las 13:29

1 respuesta 1

1

Estás complicando demasiado la consulta. Lo primero que debes hacer es tomar los totales por año. Una vez con eso, puedes usar la funciones de ventana (windowing functions) para obtener totales y datos previos.

WITH Ventas AS(
    SELECT YEAR( o.ShippedDate) AS Año,
        o.ShipCountry     AS Pais,
        SUM(os.Subtotal + o.Freight) AS Monto
    FROM [Order Subtotals] AS OS
    JOIN Orders AS O ON OS.OrderID = O.OrderID
    WHERE ShippedDate IS NOT NULL
    GROUP BY YEAR( o.ShippedDate),
        o.ShipCountry
)
SELECT  Año,
        Pais,
        Monto,
        CAST( Monto * 100. / SUM( Monto) OVER( PARTITION BY Año) AS decimal( 8, 4)) AS Porcentaje,
        Monto - LAG( Monto, 1, 0) OVER( PARTITION BY Pais ORDER BY Año) AS Diferencia
FROM Ventas
ORDER BY Año, Pais;

En caso de estar usando las versiones 2005, 2008 o 2008R2, la función LAG no está disponible y se tiene que solucionar de una forma un poco distinta.

WITH Ventas AS(
    SELECT YEAR( o.ShippedDate) AS Año,
        o.ShipCountry     AS Pais,
        SUM(os.Subtotal + o.Freight) AS Monto
    FROM [Order Subtotals] AS OS
    JOIN Orders AS O ON OS.OrderID = O.OrderID
    WHERE ShippedDate IS NOT NULL
    GROUP BY YEAR( o.ShippedDate),
        o.ShipCountry
)
SELECT  v.Año,
        v.Pais,
        v.Monto,
        CAST( v.Monto * 100. / SUM( v.Monto) OVER( PARTITION BY v.Año) AS decimal( 8, 4)) AS Porcentaje,
        v.Monto - ISNULL(vp.Monto, 0) AS Diferencia
FROM Ventas v
LEFT JOIN Ventas vp ON v.Año = vp.Año + 1  
                    AND v.Pais = vp.Pais
ORDER BY Año, Pais;
1
  • Ante todo muchas gracias y disculpa por no responder sobre la version de sql server que en si era la version la 2017 muchas gracias nuevamente sabia que podia mejorarla me estaba matando tratando de hacerla mas corta
    – Christian
    el 30 oct. 2019 a las 21:45

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.