Home > Software design >  How to group count a node in an XML column in a SQL table?
How to group count a node in an XML column in a SQL table?

Time:09-24

I have some XML data stored in a column in a SQL table that I need to get all the variables for one of the XML items group counted.

The query looks like this:

select fd.stdFormData 
from formdata fd   
where fd.FormType = '1X'

The returned data looks like this:

enter image description here

I need to group count the results of treatmentDiscussed to get something that looks like this:

enter image description here

I'm pretty novice at working with XML data in a SQL Server table, so any assistance on how to proceed I would be grateful for. Thanks in advance.

here is what I have so far as example. Unfortunatly I get a subquery error due to too may values returned

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

declare @Data XML ,
@treatmentReferrals varchar(50)   
select   @Data  =  (select  fd.Data from  formdata fd   where  fd.FormType  =  '1X' ) 
SELECT     @Data.value('(/root//treatmentDiscussed/node())[1]', 'nvarchar(max)') as treatmentDiscussed  
select  @treatmentReferrals = (SELECT     @Data.value('(/root//treatmentDiscussed/node())[1]', 'nvarchar(max)') as treatmentDiscussed )
 CREATE TABLE #Data
( 
treatmentReferrals VARCHAR(30) 
) 
INSERT INTO #Data (treatmentDiscussed)
VALUES (@treatmentDiscussed) 
 
 DROP TABLE #Data 

CodePudding user response:

Once you have used XQuery to pull out the relevant value, a GROUP BY should do the trick:

SELECT
  v.stdFormData,
  COUNT(*) count
FROM formdata fd   
CROSS APPLY fd.stdFormData.nodes('root/treatmentDiscussed') x(td)
CROSS APPLY (VALUES (td.value('text()[1]','nvarchar(10)'))) v(stdFormData)
WHERE fd.FormType = '1X'
GROUP BY
  v.stdFormData;

db<>fiddle

  • Related