Is there a way to pivot rows to columns in MySQL without using CASE?

后端 未结 1 615
悲哀的现实
悲哀的现实 2020-12-10 08:15

There are lots of posts out there on pivoting rows into columns for various databases. They seem to fall into two camps, using case statements or using a built in function

相关标签:
1条回答
  • 2020-12-10 09:10

    The link that Kangkan provided will show you how to pull this off had you known the column names in advance. We're going for the same logic, except using dynamic SQL to build the statement. There is 2 parts to each field that you need to include, the field in the select statement and an appropriate join to get the value...so we'll need to build the statement in two parts

    First declare 3 variables to build this...I'll go with @select, @join, and @sql for this example. Give the variables the initial values

     set @select = 'select user_id,'
     set @join = 'from table t'
    

    now declare and load a cursor with the distinct values in the table.key field. I'm going to use @field as the variable gets populated with the distinct table.key field. Then loop through it building the two variables:

     set @select = @select + ', ' + @field + '.value as '+@field+'
     set @join = @join + ' left join table ' + @field + 'on '+@field+'.key = t.key and and '+@field+'.user_id = t.user_id
    

    (the join is designed to use the value in @field as the alias of the table)

    loop through your cursor building out @select and @join. At the end of the loop:

    set @sql = @select + @join + 'where clause if you want'
    exec @sql
    

    Dynamic SQL built like this can be an absolute pain to trouble shoot (and get right) and open up security issues...but it's about the only way I can see this accomplished. Watch for size restrictions on your variables....if you have too many distinct Key's there, the variables grow too big. Sorry I can't be more exact with the pseudo on this...you'll find building dynamic sql in sql is painstaking.

    0 讨论(0)
提交回复
热议问题