【问题标题】:Creating separate columns based on the main column in a sql table.?根据 sql 表中的主列创建单独的列。?
【发布时间】:2020-12-17 15:42:04
【问题描述】:

我有一个包含数千条记录的表,其结构如下:

Street House Persons
1 A 2
1 B 5
1 C 3
2 D 6
2 E 9
3 F 4

我想构建一个 sql 查询,使其输出如下:

Street House Persons House Persons House Persons
1 A 2 B 5 C 3
2 D 6 E 9 null null
3 F 4 null null null null

一条街道上的房屋数量并非所有街道都相同,并且因街道而异。 有人可以帮我制定这个查询吗?谢谢!

【问题讨论】:

  • 如果有人有 4 个房子会发生什么?还是5? 7?
  • 这是一条街道上的房屋数量,与一个人拥有多少房屋无关。如果一条街道有 4/5/6 个房屋,则必须添加许多列。
  • 该评论自相矛盾;如果没关系,那么结果将“上限”为 3 组,其余的都无关紧要。
  • 我的意思是,例如,如果街道 1 有房子 G,房子里有 8 个人,那么结果表应该在街道 1 下有另一个房子和人员列,房子名称为 G 和 people如 8. 我希望我的解释是可以理解的。

标签: sql sql-server database tsql


【解决方案1】:

对于每条街道的固定最大行数,您可以使用窗口函数和聚合:

select street,
    max(case when rn = 1 then house   end) as house1,
    max(case when rn = 1 then persons end) as persons1,
    max(case when rn = 2 then house   end) as house2,
    max(case when rn = 2 then persons end) as persons2
from (
    select t.*,
        row_number() over(partition by street order by house) rn
    from mytable t
) t
group by street

您可以向select 子句添加更多条件表达式以处理每条街道的更多行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-02
    • 1970-01-01
    • 2017-10-09
    • 2013-01-19
    • 2012-09-07
    • 2020-05-05
    相关资源
    最近更新 更多