1
select               first name
              ,last name
               ,employeeID
                ,CASE
                     WHEN CONVERT(xml,detail).value('count(//education/item)','nvarchar(50)')=0 AND
                      CONVERT(xml,detail).value('(//preventive/itemValue/text())[1]','nvarchar(50)') LIKE '%Employee refuses to participate %' THEN
                           'AAA-1'

                       WHEN CONVERT(xml,detail).value('count(//education/item)','nvarchar(50)') =0 AND
                        CONVERT(xml,detail).value('count(//preventive/itemValue)','nvarchar(50)')=0 THEN
                            'AAA-2'
                        ELSE
                             'AAA-3'
                        END val

                        ,Start Date
                        ,End Date

FROM (HAS MULTIPLE JOINS HERE & CONDITION )



GROUP BY       first name
              ,last name
               ,employeeID
                ,CASE
                     WHEN CONVERT(xml,detail).value('count(//education/item)','nvarchar(50)')=0 AND
                      CONVERT(xml,detail).value('(//preventive/itemValue/text())[1]','nvarchar(50)') LIKE '%Employee refuses to participate %' THEN
                           'AAA-1'

                       WHEN CONVERT(xml,detail).value('count(//education/item)','nvarchar(50)') =0 AND
                        CONVERT(xml,detail).value('count(//preventive/itemValue)','nvarchar(50)')=0 THEN
                            'AAA-2'
                        ELSE
                             'AAA-3'
                        END 

                        ,Start Date
                        ,End Date

My code is executing perfectly fine, but when I write the group by clause it throws an error saying that XML data type cannot be grouped. I know we can do it by user defined function. Can anyone please let me know how this task can be achieved. I need to have to group by clause in my code. I'm using SQL Server 2005/2008.

4

1 回答 1

1

您可以使用交叉应用在子查询中查询您的 XML,然后在字段列表和 group by 子句中使用从子查询返回的值。

declare @T table(XMLCol xml)

insert into @T values
('<root>1</root>'),
('<root>2</root>'),
('<root>3</root>'),
('<root>3</root>')

select X.Value
from @T
  cross apply (select T.N.value('.', 'int')
               from XMLCol.nodes('root') as T(N)) as X(Value)
group by X.Value

结果:

Value
-----
1
2
3
于 2011-07-13T04:00:31.147 回答