Sql 使用子查询按指定顺序创建列

Sql 使用子查询按指定顺序创建列,sql,sql-server,Sql,Sql Server,我正在从基于oracle的Crystal Reports过渡到SQL Server/Management Studio,在更大的查询中重新创建下面的输出时遇到问题。我报告患者数据,所以我创建了一个样本表,希望能解释我需要什么。对于输出,我需要为每个客户id设置一行,并按照行号的顺序设置3个磨砂列,但只需要那些在450360中有batter_代码的磨砂列 订单: id line batter_code frosting 234 1 450

我正在从基于oracle的Crystal Reports过渡到SQL Server/Management Studio,在更大的查询中重新创建下面的输出时遇到问题。我报告患者数据,所以我创建了一个样本表,希望能解释我需要什么。对于输出,我需要为每个客户id设置一行,并按照行号的顺序设置3个磨砂列,但只需要那些在450360中有batter_代码的磨砂列

订单:

id      line    batter_code   frosting 
234     1       450           chocolate
101     1       111           Strawberry
101     2       450           Orange
101     3       360           Cherry
客户:

id    first_name  last_name
234   Jon         Smith
101   Jane        Smith
输出:

id   Last Name  First Name  Frosting 1  Frosting 2  Frosting 3
101  Smith      Jane        Orange      Cherry
234  Smith      Jon         Chocolate   

我确信这种情况已经得到了询问和回答,但我找不到。如果有解决方案,你愿意为我重定向吗?如果我需要提供澄清,请让我知道。再次感谢您的帮助。

您可以使用条件聚合:

select c.id, c.first_name, c.last_name,
       max(case when o.new_line = 1 then o.frosting end) as frosting_1,
       max(case when o.new_line = 2 then o.frosting end) as frosting_2,
       max(case when o.new_line = 3 then o.frosting end) as frosting_3
from customer c join
     (select o.*,
             row_number() over (partition by o.id order by o.line) as new_line
      from orders o
      where o.batter_code in (450, 360)
     ) o
     on c.id = o.id    
group by c.id, c.first_name, c.last_name;

关键是在进行聚合之前重新枚举行。

您可以使用条件聚合:

select c.id, c.first_name, c.last_name,
       max(case when o.new_line = 1 then o.frosting end) as frosting_1,
       max(case when o.new_line = 2 then o.frosting end) as frosting_2,
       max(case when o.new_line = 3 then o.frosting end) as frosting_3
from customer c join
     (select o.*,
             row_number() over (partition by o.id order by o.line) as new_line
      from orders o
      where o.batter_code in (450, 360)
     ) o
     on c.id = o.id    
group by c.id, c.first_name, c.last_name;

关键是在进行聚合之前重新枚举行。

另一个选项是将PIVOT与Row\u Number配合使用

范例

返回


另一个选择是使用PIVOT与Row_Number一致

范例

返回


我想你最多只能吃3个糖霜?没错,不超过3个糖霜。我想你最多只能吃3个糖霜?没错,不超过3个糖霜。非常感谢你的快速回复!非常感谢您的快速回复!
ID  first_name  last_name   Frosting 1  Frosting 2  Frosting 3
101 Jane        Smith       Orange      Cherry      NULL
234 Jon         Smith       chocolate   NULL        NULL