SQL Server SQL sum the count of populated fields grouped by another field

omvjsjqw  于 2023-10-15  发布在  其他
关注(0)|答案(2)|浏览(145)

How do I sum the count of populated fields.

An example of the data.

The desired output would be.

This is what I have managed so far.

select      m.project_ref,
        (   select count(*)
            from (values (m.[EWI/IWI]), (m.Glazing), (m.Solar), (m.CWI), (m.Boiler), (m.TRV), (m.LI), (m.RIRI), (m.UFI), (m.ASHP)) as v(col)
            where v.col <> ''
        ) as 'msr_cnt'
from        SMSDB1.dbo.ops_measure m

Thank you

mfuanj7w

mfuanj7w1#

This can be done by using the conditional aggregation :

select project_ref, sum(case when EWI_IWI <> '' then 1 else 0 end )
                    + sum(case when Glazing <> '' then 1 else 0 end ) 
                    + ... as msr_count
from mytable
group by project_ref
ldfqzlk8

ldfqzlk82#

It is not entirely clear from the data provide how you are calculating msr_count, but a simple GROUP BY might be the answer here:

SELECT
   project_ref
  ,count(*)  msr_count
 from  SMSDB1.dbo.ops_measure
 group by
   project_ref

相关问题