返回XML时如何选择Distinct

时间:2011-09-15 15:24:53

标签: sql sql-server-2008

我有一个返回XML的存储过程,现在的问题是我希望它返回不同的ClientID,但是当我这样做时......它说

The xml data type cannot be selected as DISTINCT because it is not comparable.

我该怎么做?这是我的查询

SELECT DISTINCT ClientTable.ClientID,
                ClientTable.ClientAddress,
                ClientTable.RetailStore,
                ClientTable.PhoneNumber,
                ClientTable.City,
                ClientTable.Amount,
                (SELECT Rating = IsNull(AVG(Rate), 0),
                        NumberRates = IsNUll(COUNT(ClientID), 0)
                 FROM   ReviewsTable
                 WHERE  ReviewsTable.ClientID = ClientTable.ClientID
                 FOR XML PATH(''), TYPE)
FROM   ClientTable
       INNER JOIN ClientTypes
         ON ClientTable.ClientID = ClientTypes.ClientID
WHERE  ClientTable.ClientID IN (SELECT myFreeTextTableID
                                FROM   myFreeTextTable
                                WHERE  FREETEXT(*, @Keyword))
        OR

       ClientTypes.ClientID IN (SELECT myFreeTextTableID
                                FROM   myFreeTextTable
                                WHERE  FREETEXT(*, @Keyword))

ORDER  BY ClientTable.Order ASC
FOR XML AUTO, TYPE, ELEMENTS  

1 个答案:

答案 0 :(得分:2)

我甚至不会尝试重现您的架构或数据,但这个查询呢?

;WITH ft AS
(
    SELECT ClientID = myFreeTextTableID
      FROM myFreeTextTable WHERE FREETEXT(*, @Keyword)
),
c AS
(
    SELECT DISTINCT
        c.ClientID,
        c.ClientAddress,
        c.RetailStore,
        c.PhoneNumber,
        c.City,
        c.Amount,
        c.[Order]
    FROM dbo.ClientTable AS c
    INNER JOIN dbo.ClientTypes AS t
    ON c.ClientID = t.ClientID
    WHERE EXISTS
    (
        SELECT 1 FROM ft
            WHERE ClientID IN (c.ClientID, t.ClientID)
    )
)
SELECT
    c.ClientID,
    c.ClientAddress,
    c.RetailStore,
    c.PhoneNumber,
    c.City,
    c.Amount,
    Rating = (SELECT COALESCE(AVG(Rate), 0),
                        NumberRates = COALESCE(COUNT(ClientID), 0)
                 FROM   ReviewsTable
                 WHERE  ReviewsTable.ClientID = c.ClientID
                 FOR XML PATH(''), TYPE)
FROM c
ORDER BY c.[Order]
FOR XML AUTO, TYPE, ELEMENTS;