在SQL中的一行中列出每个订单的项目
我有一个订单桌。我想从表1。
表1获得表2:
orderid | itemID |
---|---|
1 | 1 |
1 | 2 |
2 | 3 |
表2:
orderid | 项目 |
---|---|
1 | [{“ itemId”:1},{“ itemID”:2}] |
2 | [{“ itemid”:3 }] |
如何获得表2?
I have a table of orders. I want to obtain table 2 from table 1.
Table1:
OrderID | ItemId |
---|---|
1 | 1 |
1 | 2 |
2 | 3 |
Table2:
OrderID | Items |
---|---|
1 | [{"ItemId":1},{"ItemId":2}] |
2 | [{"ItemId":3}] |
How can I obtain table 2?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您使用的是SQL Server 2017或更高版本,则有
String_agg
函数,可以为您做到这一点:但是,查看串联值,看起来您正在尝试在您的SQL查询。如果是这种情况,您最好在应用程序层中进行此操作,或使用JSON 构造的
,如说明在这里。
If you're using SQL Server 2017 or above, there is
STRING_AGG
function that will do exactly this for you:However, looking at the concatenated value, it looks like you're trying to construct JSON output in your SQL query. If that is the case, you'd better be off doing this in the application layer, or using
FOR JSON
construct as explained here.在以下代码中,我将json 的
使用
选择
作为JSON。 JSON 子句格式的查询结果为JSON,而不是表。
这是代码:
In the following code, I use
FOR JSON
to formatSELECT
result as JSON. TheFOR JSON
clause format the query results as JSON, instead of table.Here is the code: