在SQL中的一行中列出每个订单的项目

发布于 2025-02-12 18:22:51 字数 868 浏览 0 评论 0原文

我有一个订单桌。我想从表1。

表1获得表2:

orderiditemID
11
12
23

表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:

OrderIDItemId
11
12
23

Table2:

OrderIDItems
1[{"ItemId":1},{"ItemId":2}]
2[{"ItemId":3}]

How can I obtain table 2?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

流年里的时光 2025-02-19 18:22:51

如果您使用的是SQL Server 2017或更高版本,则有String_agg函数,可以为您做到这一点:

SELECT OrderId, '[' + STRING_AGG('{"ItemId":' + ItemId + "}, ',') + ']' AS ItemId FROM Table1;

但是,查看串联值,看起来您正在尝试在您的SQL查询。如果是这种情况,您最好在应用程序层中进行此操作,或使用JSON 构造的,如说明在这里

If you're using SQL Server 2017 or above, there is STRING_AGG function that will do exactly this for you:

SELECT OrderId, '[' + STRING_AGG('{"ItemId":' + ItemId + "}, ',') + ']' AS ItemId FROM Table1;

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.

醉殇 2025-02-19 18:22:51

在以下代码中,我将json 的使用 选择作为JSON。 JSON 子句格式的查询结果为JSON,而不是表。

这是代码:

SELECT 
  T1.[OrderID],
  (SELECT T2.ItemId FROM OrderTable T2 WHERE T1.OrderID=T2.OrderID FOR JSON PATH) AS Items
  FROM OrderTable  AS T1
  GROUP BY T1.[OrderID] 

In the following code, I use FOR JSON to format SELECT result as JSON. The FOR JSON clause format the query results as JSON, instead of table.

Here is the code:

SELECT 
  T1.[OrderID],
  (SELECT T2.ItemId FROM OrderTable T2 WHERE T1.OrderID=T2.OrderID FOR JSON PATH) AS Items
  FROM OrderTable  AS T1
  GROUP BY T1.[OrderID] 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文