dataservice wso2 create generate response - postgresql

I would like to create a dataservice in wso2 with a query with? How to make? the query would be this:
with servicos as (
select cast(tec_servico as text) || '-' || ser_nome as servico,
ser_metodo as metodo,
coalesce(tec_vl_maximo, 0) as maximo,
teh_tipo as origem,
case when teh_dia_semana = 4410 then 0
when teh_dia_semana = 4404 then 1
when teh_dia_semana = 4405 then 2
when teh_dia_semana = 4406 then 3
when teh_dia_semana = 4407 then 4
when teh_dia_semana = 4408 then 5
when teh_dia_semana = 4409 then 6 end as dia,
teh_hora_inicial_am as hora_inicial_am,
teh_hora_final_am as hora_final_am,
teh_hora_inicial_pm as hora_inicial_pm,
teh_hora_final_pm as hora_final_pm
from tb_gcc_ted_configuracao
join tb_gfc_servico on (tec_servico = ser_cod_serial)
join tb_gcc_ted_horario on (teh_servico = tec_servico)
join tb_gen_registro on (reg_id_registro = teh_tipo)
where reg_cod_registro = :origem
and (tec_vl_maximo is null
or tec_vl_maximo > :valorLancamento)
)
select metodo
from servicos
where dia = extract(dow from current_date)
and (current_time between hora_inicial_am and hora_final_am
or current_time between hora_inicial_pm and hora_final_pm)
order by metodo
limit 1
and gives the error below:
SQL query is not applicable to automate the response
how can i do for wso2 to recognize?

Related

How to select fields using alias name?

I have an select:
SELECT
tb_dim_equipe.no_equipe "EQUIPE",
tb_dim_profissional.no_profissional "PROFISSIONAL",
no_cidadao "CIDADÃO",
a.nu_cns "CNS",
sum(case when co_dim_tempo >= 20190100 and co_dim_tempo <= 20200131 then 1 else 0 end) as "TOTAL"
from (
SELECT no_cidadao,
tb_fat_cad_individual.nu_cns,
tb_fat_cad_individual.co_dim_profissional,
tb_fat_cad_individual.co_dim_equipe from tb_fat_cidadao_pec
join tb_fat_cad_individual on tb_fat_cad_individual.nu_cns = tb_fat_cidadao_pec.nu_cns
join tb_fat_cidadao on tb_fat_cad_individual.co_seq_fat_cad_individual = tb_fat_cidadao.co_fat_cad_individual
where st_mudou = 0
and st_vivo = 1
and st_gestante = 1
and tb_fat_cidadao.co_dim_tempo_validade = 30001231) a
left join (
SELECT tb_fat_atendimento_individual.nu_cns,
tb_fat_atendimento_individual.co_dim_tempo
from tb_fat_atendimento_individual
join tb_dim_tempo on tb_dim_tempo.co_seq_dim_tempo = tb_fat_atendimento_individual.co_dim_tempo
where co_seq_dim_tempo >= 20190100
and co_seq_dim_tempo <= 20200131
and ds_filtro_ciaps like '%ABP001%'
union SELECT tb_fat_proced_atend.nu_cns,
tb_fat_proced_atend.co_dim_tempo
from tb_fat_proced_atend
join tb_dim_tempo on tb_dim_tempo.co_seq_dim_tempo = tb_fat_proced_atend.co_dim_tempo
where co_seq_dim_tempo >= 20190100
and co_seq_dim_tempo <= 20200131
and ds_filtro_procedimento like '%0301010110%') b
on a.nu_cns = b.nu_cns
join tb_dim_equipe on tb_dim_equipe.co_seq_dim_equipe = a.co_dim_equipe
join tb_dim_profissional on tb_dim_profissional.co_seq_dim_profissional = a.co_dim_profissional
group by no_equipe, no_profissional, no_cidadao, a.nu_cns
order by no_equipe, no_profissional, no_cidadao
This return to me five columns EQUIPE, PROFISSIONAL, CIDADÃO, CNS and TOTAL
I want to create a new select command like this:
SELECT sum(c.TOTAL) from *query above* c
but I receive the error that column not exists.
How I can use a select with the names of alias columns EQUIPE, PROFISSIONAL, CIDADÃO, CNS and TOTAL?
Just like in the alias, you need to quote the column identifier if it is all-uppercase:
SELECT sum(c."TOTAL") from /*query above*/ c
-- ^ ^

How can I split a T-SQL Command

How can I split a T-SQL Command in
SELECT FROM WHERE GROUP
For example i need split this command
Text To lcSQLCommand TextMerge NoShow Flags 1 Pretext 15
SELECT a.HabitacionID, a.TipoID, b.AlquilerID, b.Desde, b.Hasta, IFNULL(b.Estado, 0) Estado,
c.Habitacion, c.Precio1 Precio
FROM habitaciones a
LEFT JOIN (SELECT HabitacionID, AlquilerID, Desde, Hasta, Estado
FROM alquiler
WHERE (Estado = 2 AND Desde <= CURDATE()) OR Estado = 1
) b ON a.HabitacionID = b.HabitacionID
LEFT JOIN habitaciones_tipo c ON a.TipoID = c.TipoID
EndText
In
lcSQLSelect = "SELECT a.HabitacionID, a.TipoID, b.AlquilerID, b.Desde, b.Hasta, IFNULL(b.Estado, 0) Estado, c.Habitacion, c.Precio1 Precio"
lcSQLFrom = "FROM habitaciones a LEFT JOIN (SELECT HabitacionID, AlquilerID, Desde, Hasta, Estado FROM alquiler WHERE (Estado = 2 AND Desde <= CURDATE()) OR Estado = 1) b ON a.HabitacionID = b.HabitacionID LEFT JOIN habitaciones_tipo c ON a.TipoID = c.TipoID"
lcWhere = "" && No Where in this command
lcGroup = "" && No Group un this command
Best regards
Ze Roberto
Text To lcSQLCommand TextMerge NoShow Flags 1 Pretext 15
SELECT a.HabitacionID, a.TipoID, b.AlquilerID, b.Desde, b.Hasta, IFNULL(b.Estado, 0) Estado,
c.Habitacion, c.Precio1 Precio
FROM habitaciones a
LEFT JOIN (SELECT HabitacionID, AlquilerID, Desde, Hasta, Estado
FROM alquiler
WHERE (Estado = 2 AND Desde <= CURDATE()) OR Estado = 1
) b ON a.HabitacionID = b.HabitacionID
LEFT JOIN habitaciones_tipo c ON a.TipoID = c.TipoID EndText
In
lcSQLSelect = "SELECT a.HabitacionID, a.TipoID, b.AlquilerID, b.Desde, b.Hasta, IFNULL(b.Estado, 0) Estado, c.Habitacion, c.Precio1 Precio"
lcSQLFrom = "FROM habitaciones a LEFT JOIN (SELECT HabitacionID, AlquilerID, Desde, Hasta, Estado FROM alquiler WHERE (Estado = 2 AND Desde <= CURDATE()) OR Estado = 1) b ON a.HabitacionID = b.HabitacionID LEFT JOIN habitaciones_tipo c ON a.TipoID = c.TipoID"
lcWhere = "" && No Where in this command
lcGroup = "" && No Group un this command
Take a look at the STREXTRACT() function. It lets you pull strings apart by specifying beginning and ending delimiters. So, for example, to get the field list, you'd use:
lcFieldList = STREXTRACT(lcSQLCommand, "SELECT", "FROM")
It gets trickier for the rest of what you need because you'll have to check for the presence of the WHERE and GROUP BY keywords to know exactly what delimiters you have, but the whole thing shouldn't be more than about 15 or 20 lines.
Note: I'm assuming you want to do this in VFP.

How to append CTE results to main query output?

I've created a TSQL query that pulls from two sets of tables in my database. The tables in the Common Table Expression are different from the tables in the main query. I'm joining on MRN and need the end result to contain accounts from both sets of tables. I've written the following query to this end:
with cteHosp as(
select Distinct p.EncounterNumber, p.MRN, p.AdmitAge
from HospitalPatients p
inner join Eligibility e on p.MRN = e.MRN
inner join HospChgDtl c on p.pt_id = c.pt_id
inner join HospitalDiagnoses d on p.pt_id = d.pt_id
where p.AdmitAge >=12
and d.dx_cd in ('G89.4','R52.1','R52.2','Z00.129')
)
Select Distinct a.AccountNo, a.dob, DATEDIFF(yy, a.dob, GETDATE()) as Age
from RHCCPTDetail c
inner join RHCAppointments a on c.ClaimID = a.ClaimID
inner join Eligibility e on c.hl7Id = e.MRN
full outer join cteHosp on e.MRN = cteHosp.MRN
where DATEDIFF(yy, a.dob, getdate()) >= 12
and left(c.PriDiag,7) in ('G89.4','R52.1','R52.2', 'Z00.129')
or (
DATEDIFF(yy, a.dob, getdate()) >= 12
and LEFT(c.DiagCode2,7) in ('G89.4','R52.1','R52.2','Z00.129')
)
or (
DATEDIFF(yy, a.dob, getdate()) >= 12
and LEFT(c.DiagCode3,7) in ('G89.4','R52.1','R52.2','Z00.129')
)
or (
DATEDIFF(yy, a.dob, getdate()) >= 12
and LEFT(c.DiagCode4,7) in ('G89.4','R52.1','R52.2','Z00.129')
)
order by AccountNo
How do I merge together the output of both the common table expression and the main query into one set of results?
Merge performs inserts, updates or deletes. I believe you want to join the cte. If so, here is an example.
Notice the cteBatch is joined to the Main query below.
with
cteBatch (BatchID,BatchDate,Creator,LogID)
as
(
select
BatchID
,dateadd(day,right(BatchID,3) -1,
cast(cast(left(BatchID,4) as varchar(4))
+ '-01-01' as date)) BatchDate
,Creator
,LogID
from tblPriceMatrixBatch b
unpivot
(
LogID
for Logs in (LogIDISI,LogIDTG,LogIDWeb)
)u
)
Select
0 as isCurrent
,i.InterfaceID
,i.InterfaceName
,b.BatchID
,b.BatchDate
,case when isdate(l.start) = 0 and isdate(l.[end]) = 0 then 'Scheduled'
when isdate(l.start) = 1 and isdate(l.[end]) = 0 then 'Running'
when isdate(l.start) = 1 and isdate(l.[end]) = 1 and isnull(l.haserror,0) = 1 then 'Failed'
when isdate(l.start) = 1 and isdate(l.[end]) = 1 and isnull(l.haserror,0) != 1 then 'Success'
else 'idunno' end as stat
,l.Start as StartTime
,l.[end] as CompleteTime
,b.Creator as Usr
from EOCSupport.dbo.Interfaces i
join EOCSupport.dbo.Logs l
on i.InterfaceID = l.InterfaceID
join cteBatch b
on b.logid = l.LogID

db2 error with sum()

I am using the IBM tool 'JRS' to exctract data from 'RTC' with DB2.
I have the folowing code, wich it works just fine:
SELECT
CASE WHEN (T3.REQUEST_TYPE = 'Corretiva' OR T3.REQUEST_TYPE = 'Corretiva Interna' )
THEN (MAX(T1.ACTUAL_WORK) - MIN(T1.ACTUAL_WORK))/3600
ELSE 0
END AS CORRETIVAS_TIME,
(MAX(T1.ACTUAL_WORK) - MIN(T1.ACTUAL_WORK))/3600 AS TOTAL_TIME
FROM RICALM.VW_RQST_HISTORY T1 -- HISTORICO DA TAREFA
INNER JOIN RICALM.VW_RQST_HISTORY T0 -- HISTORICO ANTERIOR DA TAREFA
ON T0.REQUEST_HISTORY_ID = T1.PREV_REQUEST_HISTORY_ID
INNER JOIN RIDW.VW_REQUEST T2 -- TAREFA
ON T2.REQUEST_ID = T1.REQUEST_ID
INNER JOIN RIDW.VW_REQUEST_RELATIONAL_LINK LT1
ON T2.REQUEST_ID = LT1.REQUEST1_ID AND LT1.NAME = 'com.ibm.team.workitem.linktype.parentworkitem'
INNER JOIN RIDW.VW_REQUEST T3 -- CORRETIVA
ON LT1.REQUEST2_ID = T3.REQUEST_ID AND LT1.NAME = 'com.ibm.team.workitem.linktype.parentworkitem'
WHERE ( YEAR(CURRENT_TIMESTAMP)*12 + MONTH(CURRENT_TIMESTAMP) = YEAR(T1.REC_DATETIME)*12 + MONTH(T1.REC_DATETIME)
)
AND T1.ACTUAL_WORK <> T0.ACTUAL_WORK
AND T2.REQUEST_TYPE = 'Tarefa'
AND (T3.REQUEST_CATEGORY_NAME = 'SIENGE/Manutenção Contínua/MC-COMCRC' OR
T3.REQUEST_CATEGORY_NAME = 'SIENGE/Manutenção Programada/MP-COMCRC')
AND
(T1.ISSOFTDELETED = 0 AND T2.ISSOFTDELETED = 0 AND T3.ISSOFTDELETED = 0)
GROUP BY T1.REFERENCE_ID,T3.REQUEST_TYPE
Resulting on the folowing table:
corretivas_time
total_time
0 0
0 6
0 0
0 6
0 0
1 1
4 4
Now I want to get the sum of each column to compare eachother, so I make this folowing selection:
SELECT
SUM(CASE WHEN (T3.REQUEST_TYPE = 'Corretiva' OR T3.REQUEST_TYPE = 'Corretiva Interna' )
THEN (MAX(T1.ACTUAL_WORK) - MIN(T1.ACTUAL_WORK))/3600
ELSE 0
END) AS CORRETIVAS_TIME,
SUM((MAX(T1.ACTUAL_WORK) - MIN(T1.ACTUAL_WORK))/3600) AS TOTAL_TIME
And the rest is the same...
I get this error:
CRRGW5628E An com.ibm.db2.jcc.am.SqlSyntaxErrorException error
occurred when validating the input SQL string, caused by DB2 SQL
Error: SQLCODE=-112, SQLSTATE=42607, SQLERRMC=SUM, DRIVER=4.14.121.
I also tried this code:
SELECT SUM(SELECT
CASE WHEN (T3.REQUEST_TYPE = 'Corretiva' OR T3.REQUEST_TYPE = 'Corretiva Interna' )
THEN (MAX(T1.ACTUAL_WORK) - MIN(T1.ACTUAL_WORK))/3600
ELSE 0
END AS CORRETIVAS_TIME
With the rest being the same.
I got this error:
CRRGW5628E An com.foundationdb.sql.parser.SQLParserException error
occurred when validating the input SQL string, caused by Encountered
"" at line 2, column 12. Was expecting one of: .
I'm almost sure you want something like this instead:
SELECT SUM(corretivas_time), SUM(total_time) FROM (
SELECT
CASE WHEN (T3.REQUEST_TYPE = 'Corretiva' OR T3.REQUEST_TYPE = 'Corretiva Interna' )
THEN (MAX(T1.ACTUAL_WORK) - MIN(T1.ACTUAL_WORK))/3600
ELSE 0
END AS CORRETIVAS_TIME,
(MAX(T1.ACTUAL_WORK) - MIN(T1.ACTUAL_WORK))/3600 AS TOTAL_TIME
FROM RICALM.VW_RQST_HISTORY T1 -- HISTORICO DA TAREFA
INNER JOIN RICALM.VW_RQST_HISTORY T0 -- HISTORICO ANTERIOR DA TAREFA
ON T0.REQUEST_HISTORY_ID = T1.PREV_REQUEST_HISTORY_ID
INNER JOIN RIDW.VW_REQUEST T2 -- TAREFA
ON T2.REQUEST_ID = T1.REQUEST_ID
INNER JOIN RIDW.VW_REQUEST_RELATIONAL_LINK LT1
ON T2.REQUEST_ID = LT1.REQUEST1_ID AND LT1.NAME = 'com.ibm.team.workitem.linktype.parentworkitem'
INNER JOIN RIDW.VW_REQUEST T3 -- CORRETIVA
ON LT1.REQUEST2_ID = T3.REQUEST_ID AND LT1.NAME = 'com.ibm.team.workitem.linktype.parentworkitem'
WHERE ( YEAR(CURRENT_TIMESTAMP)*12 + MONTH(CURRENT_TIMESTAMP) = YEAR(T1.REC_DATETIME)*12 + MONTH(T1.REC_DATETIME)
)
AND T1.ACTUAL_WORK <> T0.ACTUAL_WORK
AND T2.REQUEST_TYPE = 'Tarefa'
AND (T3.REQUEST_CATEGORY_NAME = 'SIENGE/Manutenção Contínua/MC-COMCRC' OR
T3.REQUEST_CATEGORY_NAME = 'SIENGE/Manutenção Programada/MP-COMCRC')
AND
(T1.ISSOFTDELETED = 0 AND T2.ISSOFTDELETED = 0 AND T3.ISSOFTDELETED = 0)
GROUP BY T1.REFERENCE_ID,T3.REQUEST_TYPE
) as t

SQL "WHERE IN" query conversion to LINQ

I'm trying to find a way to convert this very complex SQL Query into LINQ and I can't seem to tackle all the embedded "WHERE IN" clauses. Would someone be so kind as to lend me a helping hand?
Here is the SQL code (don't worry about the stored procedure, it's a count of a row total)
SELECT
(SELECT pac.Name FROM Account pac WHERE pac.AccountID = AC.ParentAccountID) AS ParentAccountName,
ac.Name, dv.DeviceID, dv.Manufacturer, dv.Model, dv.SerialNr, dv.PrinterIPAddress,
(SELECT TOP 1 au.AuditDate FROM PrinterAudit pa WITH (NOLOCK) INNER JOIN Audit au ON au.AuditID = pa.AuditID
WHERE pa.DeviceID=dv.DeviceID
ORDER BY AuditDate DESC) AS AuditDate,
dbo.Get_TotalPageCountByDeviceId( DATEADD(month, -3, GETDATE()), GETDATE(), dv.DeviceID ) as TotalUsageLast3Months
FROM Account ac WITH (NOLOCK)
INNER JOIN Device dv ON ac.AccountID = dv.AccountID
WHERE dv.AccountID IN
( SELECT au.AccountID FROM Audit au WHERE au.AuditDate >= DATEADD(month, -3, GETDATE()) )
AND (dv.Manufacturer + dv.Model) IN
(SELECT (dv2.Manufacturer + dv2.Model)
FROM Device dv2
WHERE dv2.AccountID = dv.AccountID
AND dv2.Manufacturer = dv.Manufacturer
AND dv2.Model = dv.Model
AND (dv2.ERPEquipID IS NOT NULL OR dv2.ERPData IS NOT NULL ) )
AND dv.ERPEquipID IS NULL AND dv.ERPData IS NULL
AND dv.DeviceID IN
(SELECT pa.DeviceID
FROM PrinterAudit pa WITH (NOLOCK)
INNER JOIN Audit au ON au.AuditID = pa.AuditID
WHERE au.AuditDate >= DATEADD(month, -3, GETDATE()))
ORDER BY ParentAccountName, ac.Name
Final Result:
var result =
(from dv in Device
where Audit.Any(au => au.AuditDate >= DateTime.Now.AddMonths(-3)
&& au.AccountID == dv.AccountID)
where Device.Any(dv2 => dv2.AccountID == dv.AccountID
&& dv2.Manufacturer == dv.Manufacturer
&& dv2.Model == dv.Model
&& (dv2.ERPEquipID != null || dv2.ERPData != null)
&& dv.ERPEquipID == null
&& dv.ERPData == null
&& PrinterAudit.Any(pa => pa.Audit.AuditDate >= DateTime.Now.AddMonths(-3) && pa.DeviceID == dv.DeviceID))
orderby dv.Account.ParentAccountID, dv.Account.Name
select new
{
ParentAccountName = Account.Where(pac => pac.AccountID == dv.Account.ParentAccountID).Select(pac => pac.Name),
Name = dv.Account.Name,
DeviceID = dv.DeviceID,
Manufacturer = dv.Manufacturer,
Model = dv.Model,
SerialNumber = dv.SerialNr,
PrinterIPAddress = dv.PrinterIPAddress,
AuditDate = (from pa in PrinterAudit where pa.DeviceID == dv.DeviceID orderby pa.Audit.AuditDate descending select pa.Audit.AuditDate).Take(1),
TotalUsageLast3Months = (from p in PrinterAudit
where p.DeviceID == dv.DeviceID
group p by p.DeviceID into total
select new
{
Total = Get_TotalPageCountByDeviceId(DateTime.Now.AddMonths(-3), DateTime.Now, dv.DeviceID)
})
});
You convert the SQL IN statement to linq with either Contains or Any
Contains
from dv in db.Device
where
(from au in db.Audit
where au.AuditDate >= DateTime.Now.AddMonths(-3)
select au.AccountID).Contains(dv.AccountID)
Any
from dv in db.Device
where
db.Audit.Any(au => au.AuditDate >= DateTime.Now.AddMonths(-3) &&
au.AccountID == dv.AccountID)