如何在 SQL Server 中将行合并为一行
我有一个这样的表:
- ID | CurrencyID | LendID | Price
- 3 | 1 | 1 | 1.2
- 3 | 1 | 2 | 1.3
- 3 | 1 | 3 | 1.4
- 3 | 2 | 1 | 1.5
- 3 | 2 | 2 | 1.6
- 3 | 2 | 3 | 1.7
- 4 | 2 | 3 | 2.0
总共有 4 种货币 1,2,3,4
总共有 3 种借出 1,2,3
我想得到这样的结果如下:
ID | CurrencyIDLendID_11_Price | CIDID_12_Price | CIDLID_13_Price | CIDLID_21_Price | CIDLID_22_Price | CIDLID_23_Price | CIDLID_31_Price | CIDLID_32_Price | CIDLID_33_Price | CIDLID_41_Price | CIDLID_42_Price | CIDLID_43_Price
3 | 1.2 | 1.3 | 1.4 | 1.5 | 1.6 | 1.7 | 0 | 0 | 0 | 0 | 0 | 0
4 | 0 | 0 | 0 | 0 | 0 | 2.0 | 0 | 0 | 0 | 0 | 0 | 0
我知道现在这是很好的描述,但我想做的是将多条记录合并为一条记录。
I have a table like this:
- ID | CurrencyID | LendID | Price
- 3 | 1 | 1 | 1.2
- 3 | 1 | 2 | 1.3
- 3 | 1 | 3 | 1.4
- 3 | 2 | 1 | 1.5
- 3 | 2 | 2 | 1.6
- 3 | 2 | 3 | 1.7
- 4 | 2 | 3 | 2.0
There are totally 4 currencies 1,2,3,4
There are totally 3 lend 1,2,3
I want to get a result like below:
ID | CurrencyIDLendID_11_Price | CIDID_12_Price | CIDLID_13_Price | CIDLID_21_Price | CIDLID_22_Price | CIDLID_23_Price | CIDLID_31_Price | CIDLID_32_Price | CIDLID_33_Price | CIDLID_41_Price | CIDLID_42_Price | CIDLID_43_Price
3 | 1.2 | 1.3 | 1.4 | 1.5 | 1.6 | 1.7 | 0 | 0 | 0 | 0 | 0 | 0
4 | 0 | 0 | 0 | 0 | 0 | 2.0 | 0 | 0 | 0 | 0 | 0 | 0
I know it is now good description, but what I want to do is to merge many records to one record.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这称为透视,进行透视的方法之一是使用带条件聚合的分组:
如果保证所有
(CurrencyID, LendID)
组合都是唯一的在相同的 ID 组中,您还可以使用 MIN 或 MAX 来代替 SUM。This is called pivoting and one of the ways how to do the pivoting is to use grouping with conditional aggregating:
If all the
(CurrencyID, LendID)
combinations are guaranteed to be unique within same ID groups, you can also use MIN or MAX instead of SUM.您可以使用从 SQL Server 2005 开始的 PIVOT 语法,
其输出
注意:我保留了你的专栏名称
You could use the PIVOT Syntax starting with SQL Server 2005
which outputs
Note: I kept your column names