选择一行的行,在另一行选择中选择

发布于 2025-01-25 07:11:55 字数 982 浏览 1 评论 0原文

现有查询返回下表:

UserId扇区
11 1111
12122
13133
22222 2
2 22 2 2 3233
31311

,但我想以下面的方式“重新格式化”它:

UserIdSector 1 Sector 1Sector 2Sector 2 Sector 3
1111122122
2222233
3311

最大扇区数量是可变的。由于我是SQL的新手,因此我不确定这是DB类型的特定物质,因此对PostgreSQL有效的解决方案表示赞赏。

如果这是数据库中不应该完成的事情,也可以。我仍在弄清楚在数据库中该怎么做,什么不做。

我知道标题不好。如果您有更精确的建议,请提出一些建议。

An existing query returns the following table:

UserIDSectorValue
11111
12122
13133
22222
23233
31311

But I would like to "reformat" it in the following way:

UserIDSector 1Sector 2Sector 3
1111122122
2222233
3311

The maximum number of sectors is variable. Since i am new to SQL I am not sure weather this would be something DB Type Specific, so a solution which works for PostgreSQL is appreciated.

If this is something which should not be done in the database, it is also okay. I am still figuring out what to do in the database and what not.

Title is not good, I know. Please make some recommendation if you have an more precise one.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

内心旳酸楚 2025-02-01 07:11:55

不幸的是,您无法具有动态数量的列数。
这是您提供的示例数据的SQL。您必须安装TableFunc扩展名。

SELECT *
FROM crosstab(
  'select userid, sector, value
   from user_sector
   order by 1,2')
AS ct(userid int, sector1 int, sector2 int,sector3 int);

Unfortunately you cannot have dynamic number of columns.
Here is the SQL for the sample data you've provided. You must have tablefunc extension installed.

SELECT *
FROM crosstab(
  'select userid, sector, value
   from user_sector
   order by 1,2')
AS ct(userid int, sector1 int, sector2 int,sector3 int);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文