简体   繁体   English

如何在 SQL 查询中从同一张表中提取不同的 json 元素?

[英]How to extract different json elements from the same table in SQL query?

I am querying from a table with the following format:我正在从具有以下格式的表中查询:

id|provider|score
--------------------------------
1 |  att     | '{"attscore":300}'
1 |  verizon | '{"verizonscore":299}'
2 |   att    | '{"attscore":200}'
3 |  verizon | '{"verizonscore":155}'

I am trying to get a table that looks like the following:我正在尝试获取如下所示的表格:

id|attscore|verizonscore
-------------------------
1  |  300   |    299
2  |  200   |    null
3  |  null  |    155

Note that used to json in sql注意在 sql 中使用了 json

 CREATE TABLE table1 ( `id` INTEGER, `provider` VARCHAR(7), `score` VARCHAR(22) ); INSERT INTO table1 (`id`, `provider`, `score`) VALUES ('1', 'att', '{"attscore":300}'), ('1', 'verizon', '{"verizonscore":299}'), ('2', 'att', '{"attscore":200}'), ('3', 'verizon', '{"verizonscore":155}');
 SELECT id, GROUP_CONCAT(CASE WHEN provider = 'att' THEN `score`->"$.attscore" ELSe NULL END) attscore,GROUP_CONCAT(CASE WHEN provider = 'verizon' THEN `score`->"$.verizonscore" ELSe NULL END) verizonscore FROM table1 GROUP BY id
 id |编号 | attscore |攻击力 | verizonscore -: |:------- |:----------- 1 | verizoncore -: |:------- |:------------ 1 | 300 | 300 | 299 2 | 299 2 | 200 | 200 | null 3 | null 3 | null | null | 155 155

db<>fiddle here db<> 在这里摆弄

This works with a fixed number of column quite well, if you have much more of these you need to do something like this这适用于固定数量的列,如果你有更多这些,你需要做这样的事情

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在同一 SQL 查询期间计算不同表中的行数 - How to count rows from a different table during same SQL query 如何构造一个SQL查询以从同一表的不同行中获取不同的列? - How to construct a SQL query to fetch different columns from same table in different rows? sql从3个不同的表中提取相同的列 - sql to extract same columns from 3 different tables 如何在同一个表的同一个查询中使用 SUM 和 COUNT 创建 SQL - How to create SQL with SUM and COUNT in the same query from the same table SQL查询-如何提取表的最后一个孩子? - SQL QUERY - How to extract last child of a table? 如何在同一查询中从具有不同条件的表中选择数据 - How to select data from table with different conditions in the same query 如何从表中选择具有相同查询但条件不同的数据库中的数据? - How to select data from database with same query but different condition in a table? 如何在一个sql表中计算来自同一字段的不同行 - how to count different rows from the same field in one sql table SQL 查询从表中获取记录的值并更新同一表中不同记录的获取值 - SQL query to get value from the table for a record and update the fetched value for different record in the same table SQL查询...我需要从表1的同一列中插入2个值到表2的2个不同列中 - SQL query…I need to insert 2 values from same column of table1 to 2 different columns of table2
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM