Sql 不使用轴或大小写聚合函数将行转换为列
我的数据库中有一个名为customers的表,其中包含零售商(customers) 和按typeid划分的分销商(例如:typeid=1个客户和typeid=2个分销商) 现在有一个映射表,其中有客户和分销商的映射。 请注意,一个零售商或客户最多只有两个分销商 下面是映射表Sql 不使用轴或大小写聚合函数将行转换为列,sql,sql-server,sql-server-2012,Sql,Sql Server,Sql Server 2012,我的数据库中有一个名为customers的表,其中包含零售商(customers) 和按typeid划分的分销商(例如:typeid=1个客户和typeid=2个分销商) 现在有一个映射表,其中有客户和分销商的映射。 请注意,一个零售商或客户最多只有两个分销商 下面是映射表 | Customer | Distributor | ---------------------------- | Customer1 | Distributor1 | | Cust
| Customer | Distributor |
----------------------------
| Customer1 | Distributor1 |
| Customer1 | Distributor2 |
| Customer2 | Distributor1 |
| Customer2 | Distributor3 |
| Customer3 | Distributor2 |
我想把这张表表示如下
| Customer | Partner1 | Partner 2 |
---------------------------------------------------
| Customer1 | Distributor1 | Distributor2 |
| Customer2 | Distributor1 | Distributor3 |
| Customer3 | Distributor2 | Null |
Pivot的概念打动了我,但对于要应用的Pivot,没有可执行聚合函数的列
有什么简单的方法可以达到预期的效果吗
PS:我已经考虑过从两个临时表中获取两个不同的集合,然后将它们连接起来,但这看起来很乏味。如果有人能用一个更简单的解决方案将结果告诉我,请帮助我。您可以使用
行数()
生成旋转所需的列:
您使用的是mysql还是sql server?它们不是同一件事。我删除了无关的数据库标记。请用您实际使用的数据库标记问题。@johncode我使用的是sql server 2012,它对我有用,但我不明白它的意思。如果你能解释一下你的问题到底发生了什么,那就太好了?分区的用途是什么?
select customer,
max(case when seqnum = 1 then distributor end) as distributor1,
max(case when seqnum = 2 then distributor end) as distributor2
from (select t.*,
row_number() over (partition by customer order by (select null)) as seqnum
from t
) t
group by customer;