SQL:通过排列起始项来扩展现有表



我在 vertica 数据库中有一个N x M表,我的目标是创建一个具有N*M x M的新表,以便初始表中的每一行都被 M 行替换,其中起始项入。

下面是2 x 3表的示例

+-------+-------+-------+
| Item1 | Item2 | Item3 |
+-------+-------+-------+
| A     | B     | C     |
| C     | K     | L     |
+-------+-------+-------+

成为一个6 x 3表,其中原始行的每一行都被 3 个新行替换,其中 Item1 始终是不同的起始项。

+-------+-------+-------+
| Item1 | Item2 | Item3 |
+-------+-------+-------+
| A     | B     | C     |
| B     | A     | C     |
| C     | A     | B     |
| C     | K     | L     |
| K     | C     | L     |
| L     | C     | K     |
+-------+-------+-------+

有没有一个优雅的解决方案来解决这类问题,我尝试以各种方式使用加入,但到目前为止没有运气。谢谢!!

在一般情况下我无法帮助您。在特定情况下,这在 Vertica 中是否有效?

select
case n 
when 1 then item1
when 2 then item2
else item3
end as item1,
case n 
when 1 then item2
when 2 then item3
else item1
end as item2,
case n 
when 1 then item3
when 2 then item1
else item2
end as item3
from tab
cross join (select 1 as n union all select 2 as n union all select 3 as n) as b

我自己是 SQL Server 人,从表的定义动态进行此查询会很简单(给定对表元数据的合理约束(,但唉,我不知道 Vertica

我在想为什么不直接使用一堆这样的工会

SELECT Item1, Item2, Item3 from Table
union SELECT Item2, Item3, Item1 from Table
UNION SELECT Item3, Item1, Item2 from Table

这应该给出相同的结果,不是吗?

最新更新