I need a query for to know the Subtract data from the first day vs. the last day of the month in SQL of all months of the year.
I used SQL Server and this is my current query
DECLARE @FechaInicial DATE = '2024-01-08';
DECLARE @FechaFinal DATE = '2024-02-10';
SELECT
dm.Fecha,
SUM(CASE
WHEN dm.Linea = 'ELFO_006_Oficinas'
THEN dm.Dato - ISNULL(dp.Dato, 0)
ELSE 0
END) AS ELFO_006_Oficinas_Diferencia,
SUM(CASE
WHEN dm.Linea = 'ELFO_007_Rim'
THEN dm.Dato - ISNULL(dp.Dato, 0)
ELSE 0
END) AS ELFO_007_Rim_Diferencia,
SUM(CASE
WHEN dm.Linea = 'ELFO_008_ED'
THEN dm.Dato - ISNULL(dp.Dato, 0)
ELSE 0
END) AS ELFO_008_ED_Diferencia,
SUM(CASE
WHEN dm.Linea = 'ELFO_009_FBW'
THEN dm.Dato - ISNULL(dp.Dato, 0)
ELSE 0
END) AS ELFO_009_FBW_Diferencia,
SUM(CASE
WHEN dm.Linea = 'ELFO_010_Disco'
THEN dm.Dato - ISNULL(dp.Dato, 0)
ELSE 0
END) AS ELFO_010_Disco_Diferencia
FROM
Dato_Medidor dm
LEFT JOIN
Dato_Medidor dp ON DATEADD(YY, - 1, dm.Fecha) = dp.Fecha
AND dm.Linea = dp.Linea
AND dp.Fecha BETWEEN DATEADD(DAY, 1, EOMONTH(@FechaInicial, -1)) AND DATEADD(DAY, 1, EOMONTH(@FechaFinal,-1))
AND DATEPART(HOUR, dp.Fecha) = 7
AND DATEPART(MINUTE, dp.Fecha) = 0
WHERE
dm.Fecha BETWEEN EOMONTH(@FechaInicial) AND EOMONTH(@FechaFinal)
AND DATEPART(HOUR, dm.Fecha) = 7
AND DATEPART(MINUTE, dm.Fecha) = 0
GROUP BY
dm.Fecha
ORDER BY
dm.Fecha
This is my current result:
MONTH -- | ELFO_010_Disco | ELFO_009_FBW |
---|---|---|
01/01/2024 | 100 | 300 |
01/02/2024 | 100 | 400 |
01/03/2024 | 400 | 500 |
and I need this:
MONTH | ELFO_010_Disco | ELFO_009_FBW |
---|---|---|
JENUARY | 100 | 200 |
February | 300 | 100 |
March | 0 | 0 |