sql - 如何在字符串中动态确定的位置选择动态数量的子字符串?

标签 sql postgresql tsql substring

我的数据库中有一串信息,它是一串 json,我正试图从中获取一些特定的信息。下面是一个 json 示例,我试图从每个条目中获取 SuIDQuantity。有时只有一个条目,有时有两个以上的条目,但它们总是采用这样的格式。

我尝试使用 charindexleftrightsubstringreplace,但是当我需要多个部分时,我不知道如何让它工作。

[{
    "SuID": 8348,
    "SuParentSuID": 652,
    "Quantity": 0,
    "LeadTime": 72,
    "LeadTimeClosures": 0,
    "Transships": 0,
    "InventoryStatus": 2,
    "HasCurrentFeed": 1,
    "LeadTimeSource": 0,
    "GhcPrgBitwise": 0,
    "QuantityAdjustment": 0,
    "ExclusionCriteria": 0
}, {
    "SuID": 8349,
    "SuParentSuID": 652,
    "Quantity": 454,
    "LeadTime": 72,
    "LeadTimeClosures": 0,
    "Transships": 0,
    "InventoryStatus": 1,
    "HasCurrentFeed": 1,
    "LeadTimeSource": 1,
    "GhcPrgBitwise": 0,
    "QuantityAdjustment": 0,
    "ExclusionCriteria": 0
}]

我需要得到像这张表这样的东西:

 Suid | Quantity
------|----------
 8348 |     0
 8349 |    454

最佳答案

使用 Postgres,您可以使用实际的 json 数据类型来使这个非常简单:

SELECT j->>'Suid' AS suid
     , j->>'Quantity' AS quantity
FROM   json_array_elements(my_json) j

my_jsonjson 类型的 JSON 值。
文字输入也会非常简单:

SELECT j->>'Suid' AS suid
     , j->>'Quantity' AS quantity
FROM   json_array_elements( <b>'[{
       "SuID": 8348,
       "Quantity": 0,
       ...
   }, {
       "SuID": 8349,
       "Quantity": 454,
       ...
   }]'::json</b>) j

JSON Functions and operators in the manual.

关于sql - 如何在字符串中动态确定的位置选择动态数量的子字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26894508/

相关文章:

mysql - 如果查询包含 SET,Django 原始 sql 将不起作用

非企业服务器上的 SQL 分区?

sql-server - @@OPTIONS 位掩码与 DISABLE_DEF_CNST_CHK

sql - T SQL 条件字符串连接

SQL:NOLOCK 导致查询变慢

sql - 选择相隔一秒的行

mysql - SQl 查询中的 Sub-Query 和 JOIN 哪个更好?

postgresql - Slony - slonik 语法问题

PostgreSQL:是否存在强大的第三方日期数学函数来增强内置日期运算符?

mysql - 针对无法实时发生的繁重工作负载的策略? (Web 应用程序、用户匹配、缓存)