Question

I want to sum if any values if it exists in any of three columns for the duplicated unit number. Getting error if I use below query. any help appreciated. Thank you

select RANK() OVER(PARTITION BY unitNumber order by tableA.id) as unitnumber, ColA, ColC, ColB 
from tableA join 
     tableB on tableA.id = TableB.id
where unitNumber > 1
  and tableB .adm_Date between 01-01-2013 and 12-31-2013

Data:

 unitNumber colA  colB   ColB
  235       402   88     null
  245       null  501    522
  255       110   550    null
  245       85    null   101
  215       90    null   20
  275       852   225    null
  215       70    null   20
  225       null  null   null

The output should be

  unitNumber   colA    colB    ColB
    235         402     88     null
    245          85    501     623------added the values in colA, ColB
    275         852    225     null
    215         160   null     40 ------added the calues colA and ColB
Was it helpful?

Solution

You dont need ranking functions. All you need is group by UnitNumber. I am basing the query based on your source and destination data.

SELECT UnitNumber, SUM(ISNULL(ColA, 0)) ColA, SUM(ISNULL(ColB, 0)) ColB, SUM(ISNULL(ColC, 0)) ColC 
from tableA join 
     tableB on tableA.id = TableB.id
where unitNumber > 1
  and tableB.adm_Date between 01-01-2013 and 12-31-2013
GROUP BY UnitNumber

Assuming all the data is in the same table

SELECT UnitNumber, SUM(ISNULL(ColA, 0)) ColA, SUM(ISNULL(ColB, 0)) ColB, SUM(ISNULL(ColC, 0)) ColC 
from tableA 
where unitNumber > 1
  and tableA.adm_Date between 01-01-2013 and 12-31-2013
GROUP BY UnitNumber
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top