0

I have a table with two columns. A foreign key identifier and a XML column. The XML column contains details about the foreign object. If for example my table contains the following:

1 | <details><software name="iTunes" /></details>
1 | <details><software name="iPhoto" /><software name="iTunes" /></details>
2 | <details><software name="iTunes" /><software name="MSSQL" /></details>
2 | <details><software name="Visual Studios" /></details>

How can I run a query that will get me the unique count of 'software' per entity? So for example, the expected results would be:

1 | 2
2 | 3

Where column 1 is the identifier and column two is the unique sum.

The closest I have been able to get is the following query:

SELECT
  DISTINCT
  id,
  details.value('count(/details/software)', 'int') AS SoftwareCount
FROM
  detailsTable

But its no where's near useful. (It shows a unique row for every count it finds).

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Kyle
  • 17,317
  • 32
  • 140
  • 246

1 Answers1

2
select 
    id,
    COUNT(distinct( x.sw.value('@name','varchar(50)')))
from
    detailstable
cross apply
    detailstable.details.nodes('/details/software') x(sw)
group by id
podiluska
  • 50,950
  • 7
  • 98
  • 104