Skip to content
Advertisement

SQL Group By Sum and Nulls

I have a query that fetch the sum of quantity of a certain date with a GROUP BY, but the query is giving me NULL results and not aggregating some values.

Here is the query:

Select  
     VPC.Armazem as TARMA
    ,YEAR(VPC.data) as DataTotal
    ,CASE WHEN VP.combustivel = 1 THEN ISNULL(SUM(VPL.QTD), 0) END as ADITIVADA
    ,CASE WHEN VP.combustivel = 2 THEN ISNULL(SUM(VPL.QTD), 0) END as X98
    ,CASE WHEN VP.combustivel = 3 THEN ISNULL(SUM(VPL.QTD), 0) END as X95
    ,CASE WHEN VP.combustivel = 4 THEN ISNULL(SUM(VPL.QTD), 0) END as XGAS
    ,CASE WHEN VP.combustivel = 5 THEN ISNULL(SUM(VPL.QTD), 0) END as XGPL
    ,CASE WHEN VP.combustivel = 6 THEN ISNULL(SUM(VPL.QTD), 0) END as XAGR
    ,CASE WHEN VP.combustivel = 7 THEN ISNULL(SUM(VPL.QTD), 0) END as MISTURA
    ,CASE WHEN VP.combustivel = 9 THEN ISNULL(SUM(VPL.QTD), 0) END as XAQ
    ,CASE WHEN VP.combustivel = 10 THEN ISNULL(SUM(VPL.QTD), 0) END as ADIESEL
    ,CASE WHEN VP.combustivel = 11 THEN ISNULL(SUM(VPL.QTD), 0) END as ADBLUE
    ,CASE WHEN VP.combustivel = 12 THEN ISNULL(SUM(VPL.QTD), 0) END as O95
    ,CASE WHEN VP.combustivel = 13 THEN ISNULL(SUM(VPL.QTD), 0) END as O98
FROM
    where
    (MONTH(VPC.data) >= MONTH('2015-09-01') AND MONTH(VPC.data) <= MONTH('2015-09-01'))
    and (YEAR(VPC.data) >= YEAR('2014-09-01') AND YEAR(VPC.data) <= YEAR('2015-09-01'))
    and (VPT.armazem='454' or Len('454')=0)
    and FACT_VD NOT IN ('A', 'I', 'G', 'M')
GROUP BY
     YEAR(VPC.data)
    ,VPC.Armazem
    ,VP.combustivel
ORDER BY
     VPC.Armazem
    ,YEAR(VPC.data)

How can I aggregate the result to only show per year?

I’m using MS SQL

Advertisement

Answer

I suspect you want conditional aggregation:

Select VPC.Armazem as TARMA, YEAR(VPC.data) as DataTotal,
       SUM(CASE WHEN VP.combustivel = 1 THEN VPL.QTD ELSE 0 END) as ADITIVADA,
       SUM(CASE WHEN VP.combustivel = 2 THEN VPL.QTD ELSE 0 END) as X98,
       . . .
FROM . . .
GROUP BY YEAR(VPC.data), VPC.Armazem
. . .

Note that VP.combustivel is not in the GROUP BY.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement