且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在不使用UNIONS的情况下,使用MySQL将行转换为列?

更新时间:2023-02-15 11:10:34

我从本书

I got this out of the book The Art of SQL, pages 284-286:

假设您的表名是foo.

首先,创建一个名为pivot的表:

First, create a table called pivot:

CREATE Table pivot (
  count int
);

向该表中插入与要在foo中进行透视的列一样多的行.由于您要在foo中有三列要进行透视,因此请在透视表中创建三行:

Insert into that tables as many rows as there are columns that you want to pivot in foo. Since you have three columns in foo that you want to pivot, create three rows in the pivot table:

insert into pivot values (1);
insert into pivot values (2);
insert into pivot values (3);

现在在foopivot之间进行笛卡尔联接,使用CASE根据计数选择正确的列:

Now do a Cartesian join between foo and pivot, using a CASE to select the correct column based on the count:

SELECT foo.id, Case pivot.count
  When 1 Then cat
  When 2 Then one_above
  When 3 Then top_level
End Case
FROM foo JOIN pivot;

这应该给您您想要的东西.

This should give you what you want.