PostgreSQL specifying a JSON field as other JSON - json

I want to get json out of my PostgreSQL database running version:
PostgreSQL 9.3.1 on x86_64-unknown-linux-gnu, compiled by gcc (GCC)
4.4.7 20120313 (Red Hat 4.4.7-3), 64-bit
The data I am trying to get is like:
{
"a" : "value",
"b" : {
"c" : "some_vaue here"
}
}
I am getting value from one table and some_value from some other table using join.
How can I achieve that?
Here is something similar, but I'm getting an error:
QUERY="
SELECT row_to_json(o) FROM (
SELECT oltl.id::text as ordinal,
oltl.nid as code,
oltl.description as description,
SELECT row_to_json(j)
FROM ( SELECT cilantag.tag as code ) AS j
from olt_languages oltl
inner join ci_language_tags cilantag
on oltl.ci_language_tag_id=cilantag.id
) AS o";
The error I am getting is
ERROR: syntax error at or near "SELECT"
LINE 1: ...oltl.nid as code,oltl.description as description, SELECT row...
^ `
enter code here

A subquery in a select list has to be enclosed in brackets, try:
SELECT row_to_json(o)
FROM (
SELECT
oltl.id::text AS ordinal,
oltl.nid AS code,
oltl.description AS description,
( -- added
SELECT row_to_json(j)
FROM (
SELECT cilantag.tag AS code
) AS j
) AS tags -- + alias
FROM olt_languages oltl
INNER JOIN ci_language_tags cilantag
ON oltl.ci_language_tag_id=cilantag.id
) AS o

Related

Extract single json object from rows with column values as json key and value

I have the following table with my attempt at extracting what I would like:
with pv as (
select 2 as user_id,'StaffDashboard' as panel_class, 'wip_fields_rg' as widget_reference, 'hours' as widget_value
union all select 2,'StaffDashboard','display_rg','calendar'
union all select 2,'MatterHome','option_rg','afe'
)
select json_agg(obj)
from pv,
json_build_object(pv.panel_class, json_build_object(pv.widget_reference,pv.widget_value)) obj
where pv.user_id = 2;
This returns the following:
[{"StaffDashboard" : {"wip_fields_rg" : "hours"}}, {"StaffDashboard" : {"display_rg" : "calendar"}}, {"MatterHome" : {"option_rg" : "afe"}}]
user_id, panel_class and widget_reference provide a unique key. json_agg is obviously the wrong method. What I would like is the following:
{
"StaffDashboard" : {"wip_fields_rg" : "hours","display_rg" : "calendar"},
"MatterHome" : {"option_rg" : "afe"}
}
i.e. widget_reference and widget_value 'grouped' by panel_class. The intention is to return the json to the browser to provide user preferences for certain widgets. Any ideas gratefully received.
You can try this :
with pv as (
select 2 as user_id,'StaffDashboard' as panel_class, 'wip_fields_rg' as widget_reference, 'hours' as widget_value
union all select 2,'StaffDashboard','display_rg','calendar'
union all select 2,'MatterHome','option_rg','afe'
), panel as(
select pv.panel_class, json_object_agg(pv.widget_reference,pv.widget_value) as content
from pv
where pv.user_id = 2
group by pv.panel_class
)
select json_object_agg(panel_class, content)
from panel

CTE + INSERT INTO + SQLAlchemy

I am trying to insert some date into another table. At first I´ve tried to use sqlalchemy to create such queries, but as I got some error when executing, I tried to solve it through raw SQL, but the error still the same.
I am not very used to CTE commands, so I don´t know if there are some restrinctions over them.
WITH Conv_Pre_Pagos AS
(SELECT CONVENIO.COD_IDEN, CONVENIO.D_CLIENTE_NOM
FROM db2rpc.CONVENIO
WHERE CONVENIO.COD_ESPC = 52)
INSERT INTO DB2I023A.ANL_TARF_PAGAS_PREPAGO (convenio, convenente) SELECT CBR_TARF_REC.NR_DOC_SIS_OGM, Conv_Pre_Pagos.D_CLIENTE_NOM
FROM DB2TFA.CBR_TARF_REC JOIN Conv_Pre_Pagos ON CBR_TARF_REC.NR_DOC_SIS_OGM = Conv_Pre_Pagos.COD_IDEN
The sentence is bigger, but I removed some data to bring it cleaner. Still, the same error:
ibm_db_dbi::ProgrammingError: SQLNumResultCols failed: [IBM][CLI Driver][DB2] SQL0199N The use of the reserved word "INSERT" following "INSERT" is not valid.
Expected tokens may include: "(SELECT ,". SQLSTATE=42601 SQLCODE=-199
[SQL: WITH Conv_Pre_Pagos AS (SELECT CONVENIO.COD_IDEN, CONVENIO.D_CLIENTE_NOM
FROM db2rpc.CONVENIO WHERE CONVENIO.COD_ESPC = 52)
INSERT INTO DB2I023A.ANL_TARF_PAGAS_PREPAGO (convenio, convenente)
SELECT CBR_TARF_REC.NR_DOC_SIS_OGM, Conv_Pre_Pagos.D_CLIENTE_NOM
FROM DB2TFA.CBR_TARF_REC JOIN Conv_Pre_Pagos ON CBR_TARF_REC.NR_DOC_SIS_OGM = Conv_Pre_Pagos.COD_IDEN]
(Background on this error at: https://sqlalche.me/e/14/f405)"
Where does it see an "insert following insert"?
Try this:
INSERT INTO DB2I023A.ANL_TARF_PAGAS_PREPAGO (convenio, convenente)
WITH Conv_Pre_Pagos AS
(
SELECT CONVENIO.COD_IDEN, CONVENIO.D_CLIENTE_NOM
FROM db2rpc.CONVENIO
WHERE CONVENIO.COD_ESPC = 52
)
SELECT CBR_TARF_REC.NR_DOC_SIS_OGM, Conv_Pre_Pagos.D_CLIENTE_NOM
FROM DB2TFA.CBR_TARF_REC
JOIN Conv_Pre_Pagos ON CBR_TARF_REC.NR_DOC_SIS_OGM = Conv_Pre_Pagos.COD_IDEN

Creating new table from existing select statement

I am creating a new table into database. My code is below
CREATE TABLE Master_data AS
select a.*, COALESCE(b.content_view,0) as content_view, COALESCE(b.headline_view,0) as headline_view
FROM [Britannia_MMx_2021].[dbo].[Sales_20210323] a
left join [Britannia_MMx_2021].[dbo].[Doximity_20220328] b on a.NPI = b.NPI
and a.Year_Mon = b.Date;
I am getting this error
Msg 102, Level 15, State 1, Line 46
Incorrect syntax near '('.
Your SQL snippet displays characteristics of TSQL. In TSQL (e.g. in MS SQL Server) you do not use "create table as" followed by a select statement, instead you use an INTO clause e.g.
SELECT a.*
, COALESCE(b.content_view, 0) AS content_view
, COALESCE(b.headline_view, 0) AS headline_view
INTO Master_data
FROM [Britannia_MMx_2021].[dbo].[Sales_20210323] a
LEFT JOIN [Britannia_MMx_2021].[dbo].[Doximity_20220328] b ON a.NPI = b.NPI
AND a.Year_Mon = b.DATE;
In MySQL you do use CREATE TABLE [ IF NOT EXISTS ] new_table [ AS ]

Using "IN" in importing data from a JSON to postgresql

I'm importing some data from a JSON file, but I can't use the IN operator in the query, as it generates an error. But it works when I use only 1 condition.
Below is the code:
with dados as (
select SPLIT_PART (sar_conteudo::text, 'header":', 2) as conteudo
from tb_gcc_situacao_arquivo
where sar_arquivo = 5012
--and sar_dt_movimento = '2022-01-12'), --> That's how it works
and sar_dt_movimento in ('2021-12-30','2021-12-31','2022-01-03')), --> not like this
dados_2 as (
select left (conteudo, length(conteudo)-1) as conteudo_2 from dados),
dados_final as(
SELECT *
from json_to_recordset((select * from dados_2)::json)
as x
("textoLinhaOriginal" text, "descricaoMensagem" text))
select
substring("textoLinhaOriginal",171,18) as captacao, "descricaoMensagem"
from dados_final
where "textoLinhaOriginal" ilike 'RDB 1INCL%'
and "descricaoMensagem" <> 'EXECUCAO OK'
Searching the internet, I noticed that the json_to_recordset only takes one line. So when passing more than 1 parameter, it will return an error message. How can I resolve this?
ERROR: more than one row returned by a subquery used as an expression

Error in hive query Invalid table alias

This is my hive query
INSERT OVERWRITE TABLE bts_monthly_points_liability_rollforward
SELECT currMonth.businessEventType,
prevMonth.totalFaceValue,
prevMonth.totalAccountingValue,
currMonth.earnedFaceValue,
currMonth.earnedAccountingValue,
currMonth.expiredFaceValue,
currMonth.expiredAccountingValue,
currMonth.earnedPointsReturnFaceValue,
currMonth.earnedPointsReturnAccountingValue,
currMonth.spendPointsFaceValue,
currMonth.spendPointsAccountingValue,
currMonth.spendPointsReturnFaceValue,
currMonth.spendPointsReturnAccountingValue,
currMonth.adjustmentFaceValue,
currMonth.adjustmentAccountingValue,
currMonth.totalFaceValue,
currMonth.totalAccountingValue
FROM
(
SELECT business_event_type AS businessEventType,
SUM(earned_face_value) AS earnedFaceValue,
SUM(earned_accounting_value) AS earnedAccountingValue,
SUM(expired_face_value) AS expiredFaceValue,
SUM(expired_accounting_value) AS expiredAccountingValue,
SUM(earned_return_face_value) AS earnedPointsReturnFaceValue,
SUM(earned_return_accounting_value) AS earnedPointsReturnAccountingValue,
SUM(spend_face_value) AS spendPointsFaceValue,
SUM(spend_accounting_value) AS spendPointsAccountingValue,
SUM(spend_return_face_value) AS spendPointsReturnFaceValue,
SUM(spend_return_accounting_value) spendPointsReturnAccountingValue,
CAST(0 AS BIGINT) AS adjustmentFaceValue,
CAST(0 AS BIGINT) AS adjustmentAccountingValue,
(SUM(earned_face_value)+SUM(expired_face_value)+SUM(earned_return_face_value)+SUM(spend_face_value)+SUM(spend_return_face_value)) AS totalFaceValue,
(SUM(earned_accounting_value)+SUM(expired_accounting_value)+SUM(earned_return_accounting_value)+SUM(spend_accounting_value)+SUM(currMonth.spend_return_accounting_value)) AS totalAccountingValue
FROM ${pointsApplicationName}_points_balance
WHERE unix_timestamp(accounting_date,'yyyy-MM-dd') >= unix_timestamp("${startDate}",'yyyy-MM-dd') AND unix_timestamp(accounting_date,'yyyy-MM-dd') < unix_timestamp("${endDate}",'yyyy-MM-dd')
GROUP BY business_event_type
)currMonth
JOIN
(
SELECT business_event_type AS businessEventType,
(SUM(earned_face_value)+SUM(expired_face_value)+SUM(earned_return_face_value)+SUM(spend_face_value)+SUM(spend_return_face_value)) AS totalFaceValue,
(SUM(earned_accounting_value)+SUM(expired_accounting_value)+SUM(earned_return_accounting_value)+SUM(spend_accounting_value)+SUM(spend_return_accounting_value)) AS totalAccountingValue
FROM ${pointsApplicationName}_points_balance
WHERE unix_timestamp(accounting_date,'yyyy-MM-dd') >= unix_timestamp("${previousMonthStartDate}",'yyyy-MM-dd') AND unix_timestamp(accounting_date,'yyyy-MM-dd') < unix_timestamp("${startDate}",'yyyy-MM-dd')
GROUP BY business_event_type
)prevMonth
ON prevMonth.businessEventType = currMonth.businessEventType;
Error that I am receiving after running this query:
SemanticException [Error 10004]: Line 38:129 Invalid table alias or column reference 'currMonth': (possible column names are: business_event_type, accounting_date, earned_face_value, earned_accounting_value, expired_face_value, expired_accounting_value, earned_return_face_value, earned_return_accounting_value, spend_face_value, spend_accounting_value, spend_return_face_value, spend_return_accounting_value)
Command exiting with ret '255'
The problem is the line 35 of your query. Here's how the query works:
SELECT ...
FROM (
SELECT business_event_type AS businessEventType,
...
(SUM(earned_accounting_value)+SUM(expired_accounting_value)+SUM(earned_return_accounting_value)+SUM(spend_accounting_value)+SUM(currMonth.spend_return_accounting_value)) AS totalAccountingValue
FROM ${pointsApplicationName}_points_balance
...
)currMonth
JOIN (...)prevMonth
ON prevMonth.businessEventType = currMonth.businessEventType;
Here you can see that you are using currMonth alias inside of the subquery that aliased as currMonth. The alias does not exist in this context, this is why you get an error. It should be like this:
(SUM(earned_accounting_value)+SUM(expired_accounting_value)+SUM(earned_return_accounting_value)+SUM(spend_accounting_value)+SUM(spend_return_accounting_value)) AS totalAccountingValue