SQL: List/aggregate 一个对应交易 ID 的所有项目

SQL: List/aggregate all items for one corresponding transaction id

我在 vertica 数据库中有以下 table:

+-----+------+
| Tid | Item |
+-----+------+
|   1 | A    |
|   1 | B    |
|   1 | C    |
|   2 | B    |
|   2 | D    |
+-----+------+

我想得到这个 table:

+-----+-------+-------+-------+
| Tid | Item1 | Item2 | Item3 |
+-----+-------+-------+-------+
|   1 | A     | B     | C     |
|   2 | B     | D     |       |
+-----+-------+-------+-------+

请记住,我不知道 transaction_id (Tid) 可以拥有的最大项目数,并且每个 Tid 的项目数量不是恒定的。我尝试使用 join 和 where 但无法使其正常工作。感谢您的帮助。

你可以试试这个:

Create table #table(id int,Value varchar(1))

insert into #table 
select 1,'A'
union
select 1,'B'
union
select 1,'C'
union
select 2,'B'
union 
select 2,'D'
select id,[1] Item1,[2] Item2,[3] Item3 from
(
select id,Dense_rank()over(partition by id order by value)Rnak,Value from #table
)d
Pivot
(Min(value) for Rnak in ([1],[2],[3]))p

drop table #table

Vertica 中没有 PIVOT 功能。不能将列动态定义为查询的一部分。你必须指定。

也许还有其他选择,例如使用 UDX 将它们连接成一个聚合体,例如您将在 中找到的内容。但这会将它们放在一个字段中。

唯一的其他选择是使用 Python 之类的东西在客户端构建枢轴。否则你必须有办法为你的查询生成列列表。

对于我的示例,我假设您正在处理一个唯一的 (Tid, Item) 集。您可能需要进行修改以满足您的需要。

首先,如果您需要支持的项目,您需要确定最大数量:

with Tid_count as (
    select Tid, count(*) cnt
    from mytable
    group by 1
) 
select max(cnt)
from Tid_count;

假设您必须支持的最多项目是 4,那么您将生成一个 sql 来进行调整:

with numbered_mytable as (
    select Tid, 
           Item,
           row_number() over (partition by Tid order by Item) rn
    from   mytable
)
select Tid,
       MAX(decode(rn,1,Item)) Item1,
       MAX(decode(rn,2,Item)) Item2,
       MAX(decode(rn,3,Item)) Item3,
       MAX(decode(rn,4,Item)) Item4
from numbered_mytable
group by 1
order by 1;

或者如果您不想生成 SQL,但知道您永远不会拥有超过 X 个项目,您可以只创建一个转到 X 的静态表单。