I need to get a count of rows, after I use cross apply to expand a delimited field. The end result is I want to run this over my entire table(not very big) and get a count of report id's for a host.
For example, to keep it fairly simple I have a hostname that is associated to a field called reports. Reports is actually a comma delimited list of report id's. So in this table I have 1 host record and a reports field. like this
hostname | reports |
host1 | rpt1, rpt2,rpt3,rpt4|
host2 | rpt6,rpt8 |
etc..
I'm using cross apply to expand the reports field out and give me multiple rows like below.
basic query
select hostname, report
from tableA as a, cross apply DelimitedSplit(report,',') as tableB
where a.status = 'active'
and a.hostname = 'host1'
output:
hostname | Report
host1 | rpt1
host1 | rpt2
host1 | rpt3
etc..
then I wanted to get a count, so I tried adding a count
select hostname, report,count(report) as rpt_count
from tableA as a, cross apply DelimitedSplit(report,',') as tableB
where a.status = 'active'
and a.hostname = 'host1'
this only added a 1 next to each row, but I want 1 row and account of reports like this
hostname | report
host1 | 15
I then tried to make this a subquery with a count on the outside.
select count(*) as rpt_count (
select hostname, report
from tableA as a, cross apply DelimitedSplit(report,',') as tableB
where a.status = 'active'
and a.hostname = 'host1'
)
as work_table
where hostname = 'host1'
but the count is way off. Any ideas? I'd like to be able to do this without specifying the host, so I could run it over my entire table. Thanks in advance.