Advertisement
EmilianoRoldanR

Delivery API - Reporte pedidos por hora por dia

Nov 23rd, 2024
211
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
SQL 1.82 KB | None | 0 0
  1. /*
  2.     Obtener pedidos por hora por día y la ultima columna es un promedio.
  3. */
  4.  
  5. DECLARE @ColumnasDinamicas NVARCHAR(MAX);
  6. DECLARE @ConsultaFinal NVARCHAR(MAX);
  7. DECLARE @FechaInicio DATE = '2024-11-21'; /*DESDE ESTE DIA EN ADELANTE*/
  8.  
  9. -- Construir las columnas dinámicamente usando fechas existentes en la tabla
  10. SELECT @ColumnasDinamicas = STUFF((
  11.     SELECT DISTINCT ',' + QUOTENAME(CAST(fechacreado AS DATE))
  12.     FROM ordenes
  13.     WHERE CAST(fechacreado AS DATE) BETWEEN @FechaInicio AND CAST(GETDATE() AS DATE)
  14.     FOR XML PATH(''), TYPE
  15. ).VALUE('.', 'NVARCHAR(MAX)'), 1, 1, '');
  16.  
  17. IF @ColumnasDinamicas IS NULL
  18. BEGIN
  19.     PRINT 'No hay datos para las fechas especificadas';
  20.     RETURN;
  21. END;
  22.  
  23. SET @ConsultaFinal = '
  24. SELECT
  25.    Hora,
  26.    ' + @ColumnasDinamicas + ',
  27.    CAST((ISNULL(' +
  28.     STUFF((
  29.         SELECT '+ISNULL(' + QUOTENAME(CAST(fechacreado AS DATE)) + ',0)'
  30.         FROM ordenes
  31.         WHERE CAST(fechacreado AS DATE) BETWEEN @FechaInicio AND CAST(GETDATE() AS DATE)
  32.         GROUP BY CAST(fechacreado AS DATE)
  33.         FOR XML PATH('')
  34.     ), 1, 1, '') + ', 0)) /
  35.    (SELECT COUNT(DISTINCT CAST(fechacreado AS DATE))
  36.     FROM ordenes
  37.     WHERE CAST(fechacreado AS DATE) BETWEEN ''' + CAST(@FechaInicio AS VARCHAR(10)) + ''' AND CAST(GETDATE() AS DATE)
  38.    ) AS DECIMAL(10,2)) as Promedio_Fila
  39. FROM (
  40.    SELECT
  41.        DATEPART(HOUR, fechacreado) AS Hora,
  42.        CAST(fechacreado AS DATE) AS Fecha,
  43.        COUNT(*) AS Cantidad
  44.    FROM ordenes
  45.    WHERE CAST(fechacreado AS DATE) BETWEEN ''' + CAST(@FechaInicio AS VARCHAR(10)) + ''' AND CAST(GETDATE() AS DATE)
  46.    GROUP BY DATEPART(HOUR, fechacreado), CAST(fechacreado AS DATE)
  47. ) AS SourceTable
  48. PIVOT (
  49.    SUM(Cantidad)
  50.    FOR Fecha IN (' + @ColumnasDinamicas + ')
  51. ) AS PivotTable
  52. ORDER BY Hora;';
  53.  
  54. EXEC sp_executesql @ConsultaFinal;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement