【问题标题】:Syntax issue SQL Server. Combining Pivot, XML parse and JOIN语法问题 SQL Server。结合 Pivot、XML 解析和 JOIN
【发布时间】:2013-06-24 16:42:51
【问题描述】:

我在 SQL 表中有以下形式的列 (varchar400):

Info
User ID=1123456,Item ID=6685642

这个列是用来存储我们数据库中产品的属性的,所以虽然我只关心User ID和Item ID,但这里可能存储了多余的信息,例如:

   Info
   Irrelevant ID=666,User ID=123124,AnotherIrrelevantID=1232342,Item ID=1213124

所以我有一个如下的 SQL 查询:

-- convert info column to xml type
; with cte as --imports a library of common table expressions
(
    select TOP 1000 cast('<info ' + REPLACE(REPLACE(REPLACE(REPLACE(OtherInformation,' ', ''),',', '" '),'=','="'),'.','') + '" />' as XML) info, --puts the OtherInformation column into well formed XML
    ROW_NUMBER() over (order by TableID) id --returns all rows??
    FROM Table
    WHERE TableEnum=51
) 
SELECT DISTINCT UserID from --selects unique user ids from our returned xml
(
       select T.N.value('local-name(.)', 'varchar(max)') as Name, --selects all attributes returned in varchar(max) format as Name
       T.N.value('.', 'varchar(max)') as Value, id --Selects all values returned
       from cte cross apply info.nodes('//@*') as T(N) -- from the XML we created above
) v
pivot (max(value) for Name in ([UserID])) p --creates a pivot table on Name, separating all of the attributes into different columns

现在,这正确地返回了一个列,如下所示:

UserID
1
2
3
4
5

现在我有另一个表Table2,它保存着用户下的订单。我想将 UserID 用作此表的引用,因此我将返回此表上的行,其中我在上面返回的 UserID 等于此表中的行,而不是只返回 UserID。

所以,我们得到的是:

UserID    Table2Col   Table2Col2
2              Info        Info
5              Info        Info
5              Info2       Info2
5              Info3       Info3

2 个问题 - 我如何执行 JOIN 或执行子查询来组合这两个表,我无法弄清楚如何使用正确的语法来执行此操作。 其次,我在上面的查询中编写了一些 cmets,显示了我如何理解查询的工作原理。他们是对的吗?

【问题讨论】:

    标签: sql sql-server database sql-server-2005 select


    【解决方案1】:

    我很可能遗漏了您的问题,但您似乎可以通过以下方式扩展现有查询。这仍然使用 CTE 和 PIVOT,但是 PIVOT 查询被放置在一个子查询中,它允许您加入到table2

    ; with cte as --imports a library of common table expressions
    (
        select TOP 1000 cast('<info ' + REPLACE(REPLACE(REPLACE(REPLACE(OtherInformation,' ', ''),',', '" '),'=','="'),'.','') + '" />' as XML) info 
          , ROW_NUMBER() over (order by TableID)) id 
        FROM yourtable
    ) 
    select d.userid, t2.col1, t2.col2
    from
    (
      SELECT DISTINCT UserID 
      from 
      (
        select T.N.value('local-name(.)', 'varchar(max)') as Name, 
          T.N.value('.', 'varchar(max)') as Value, id 
        from cte 
        cross apply info.nodes('//@*') as T(N) 
      ) v
      pivot 
      (
        max(value) 
        for Name in ([UserID])
      ) p 
    ) d
    inner join table2 t2
      on d.userid = t2.userid;
    

    SQL Fiddle with Demo

    【讨论】:

    • 谢谢!今晚将对其进行测试,但这看起来不错:)。我上面的 cmets 是否正确?
    猜你喜欢
    • 2011-07-09
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 2021-12-18
    • 1970-01-01
    • 1970-01-01
    • 2017-08-01
    • 2020-04-09
    相关资源
    最近更新 更多