【问题标题】:SQL: Expand existing table by permutating the starting itemSQL:通过排列起始项来扩展现有表
【发布时间】:2017-08-07 12:34:08
【问题描述】:

我在一个 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     |
+-------+-------+-------+

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

【问题讨论】:

  • 没有优雅的解决方案。
  • 我害怕这个答案。

标签: sql combinations permutation vertica


【解决方案1】:

在一般情况下,我无法为您提供帮助。在特定情况下,这是否适用于 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

【讨论】:

  • 这适用于 Vertica,我正在使用 python 生成我的查询,所以我将尝试提出一个适用于一般情况的例程。感谢您的意见。
【解决方案2】:

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

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

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

【讨论】:

    猜你喜欢
    • 2021-05-07
    • 2015-12-06
    • 1970-01-01
    • 1970-01-01
    • 2014-07-19
    • 2021-12-28
    • 1970-01-01
    • 2023-01-05
    • 1970-01-01
    相关资源
    最近更新 更多