Convert SQL query to sqlachemy for complex query - sqlalchemy

WITH suite_table(parent_id, parent_name, child_name, parent_description, child_description) as
(
Select
test_suite.id, test_suite.name,
(Select test_suite.name from test_suite where id = sub_test_suites.child_suite_id) as child_name,
test_suite.description,
(Select test_suite.description from test_suite where id = sub_test_suites.child_suite_id) as child_description
from
test_suite
left join sub_test_suites on test_suite.id = sub_test_suites.parent_suite_id
) select
suite_table.parent_name, json_agg(case when suite_table.child_name is not null then
json_build_object(suite_table.child_name,
json_build_object(‘description’,suite_table.child_description))
else
null end )
from suite_table
group by suite_table.parent_name
;
Please provide sqlalchemy query. Its challenging but appreciate. I did not find tool to translate auomatically but sqlitis dont support WITH etc.

Related

Include another select column based on data - MySQL

How do I include SUM((pm.Quantity * bl.TotalQty)) AS NextBOMItemCount WHERE projectbomlist.ParentPartNum = bl.PartNum?
The data should not be changed, the same data should be retrieved, the however additional column has to be included.
VIEW: `NEWprojectBOMItemCount
select
`pm`.`ProjectCode` AS `ProjectCode`,
`bl`.`PartNum` AS `PartNum`,
sum((`pm`.`Quantity` * `bl`.`TotalQty`)) AS `BOMItemCount`,
`bl`.`mp` AS `mp`,
`p`.`complete` AS `complete`,
`bl`.`RMInd` AS `RMInd`,
`bl`.`M_PartNum` AS `M_PartNum`
from
(
(`projectmachine` `pm` join `projectbomlist` `bl`)
join `projects` `p`
)
where
(
(`pm`.`MachineListID` = `bl`.`MachineListID`)
and (`pm`.`ProjectCode` = `bl`.`ProjectCode`)
and (`pm`.`ProjectCode` = `p`.`ProjectCode`)
and (`p`.`AfterProjectHeirarchyInd` = 'Y')
)
and and pm.ProjectCode = 'AB212323'
group by
`pm`.`ProjectCode` ,
`bl`.`PartNum`
order by
`pm`.`ProjectCode` ,
`bl`.`PartNum`
Or, another option can be, please consider above view used in below query, please suggest changes to the below query as shown above (repeating here)
`sum((pm.Quantity * bl.TotalQty)) AS NextBOMItemCount where projectbomlist.ParentPartNum = bl.PartNum` - in place of `(select-NextBOMItemCount)`?
Please see PBLH.ParentPartNum is the column that I should compare with BL.ProjectCode to get NextBOMItemCount value.
QUERY calling view: NEWprojectBOMItemCount
Select
BL.PartNum PartNumber,
PBLH.ParentPartNum NextBOM,
(select-NextBOMItemCount),
BOMItemCount TotalQty,
PL.Description,
BL.MP as PartType,
PL.Vendor,
PL.QBType
from
NEWprojectBOMItemcount BL,
bomwiz.partslist PL,
bomwiz.projectbomlistheirarchy PBLH
Where
BL.PartNum = PL.PartNum
And BL.PartNum = PBLH.PartNum
And BL.ProjectCode = PBLH.ProjectCode
And BL.projectCode = 'AB212323'
Order By PartNumber
I think that you are looking for conditional aggregation. Your requirement could be expressed as follows:
SUM(
CASE WHEN blh.ParentPartNum = bl.PartNum
THEN pm.Quantity * bl.TotalQty
ELSE 0
END
) AS NextBOMItemCount
Let me pinpoint other issues with your query:
you have unwanted parentheses all around, and I am suspicious about the syntax of the JOINs ; you need to move conditions to the ON clause of the relevant JOIN.
every non-aggregated column must appear in the GROUP BY clause - you have missing columns there
backquotes are usually not needed
Here is an updated version of the query:
SELECT
pm.ProjectCode AS ProjectCode,
bl.PartNum AS PartNum,
SUM(pm.Quantity * bl.TotalQty) AS BOMItemCount,
SUM(
CASE WHEN blh.ParentPartNum = bl.PartNum
THEN pm.Quantity * bl.TotalQty
ELSE 0
END
) AS NextBOMItemCount,
bl.mp AS mp,
p.complete AS complete,
bl.RMInd AS RMInd,
bl.M_PartNum AS M_PartNum
FROM
projectmachine AS pm
INNER JOIN projectbomlist AS bl
ON pm.MachineListID = bl.MachineListID
AND pm.ProjectCode = bl.ProjectCode
INNER JOIN join projects AS p
ON pm.ProjectCode = p.ProjectCode
AND p.AfterProjectHeirarchyInd = 'Y'
INNER JOIN projectbomlistheirarchy blh
ON bl.ProjectCode = blh.ProjectCode
WHERE
pm.ProjectCode = 'AB212323'
GROUP BY
pm.ProjectCode,
bl.PartNum,
bl.mp,
p.complete,
bl.RMInd,
bl.M_PartNum
ORDER BY
pm.ProjectCode,
bl.PartNum

SQL query to select a value based on certain criteria

I have the following data in my Database:
Id MachineName CategoryName CounterName InstanceName RawValue
11180 SERVER64 Process ID Process w3wp#2 2068
11180 SERVER64 Process Working Set w3wp#2 9310208
Now I want to achieve that if I find the value '2068' for the "ID Process" Countername then I want to retrieve the Working Set RawValue. So based on the value of ID Process I now the [InstanceName] = w3wp#2 and therefore I want the value to retrieve = 9310208
Now I tried different SQL queries:
SELECT *
FROM [dbo].[LoadTest]
WHERE [LoadTestRunId] = '11180' and [CategoryName] = 'Process' and [InstanceName] like 'w3wp%'
But I need a filter. Can anyone guide me into the right direction?
This here will help you. I used variable because you need to find a specific ID
SQL Code
declare #myt table (id int,MachineName nvarchar(50),CategoryName nvarchar(50),CounterName nvarchar(50),InstanceName nvarchar(50),RawValue int)
insert into #myt
values
(11180 ,'SERVER64','Process','ID Process','w3wp#2',2068),
(11180 ,'SERVER64','Process','Working Set','w3wp#2',9310208)
declare #FindID int
Set #FindID = 2068;
with IdProcess as (
Select * from #myt
where RawValue = #FindID and CounterName = 'ID Process'
)
Select a.ID,a.MachineName,a.CategoryName,b.CounterName,a.InstanceName,b.RawValue from IdProcess a
inner join #myt b on a.InstanceName = b.InstanceName and b.CounterName='Working Set'
SQL Code without variable based on ID and InstanceName
with IdProcess as (
Select * from #myt
where CounterName = 'ID Process'
)
Select a.ID,a.MachineName,a.CategoryName,b.CounterName,a.InstanceName,b.RawValue from IdProcess a
inner join #myt b on a.id = b.id and a.InstanceName = b.InstanceName and b.CounterName='Working Set'
SQL Code with CategoryName filter
with IdProcess as (
Select * from #myt
where CounterName = 'ID Process' and CategoryName = 'Process'
)
Select a.ID,a.MachineName,a.CategoryName,b.CounterName,a.InstanceName,b.RawValue from IdProcess a
inner join #myt b on a.id = b.id and a.InstanceName = b.InstanceName and b.CounterName='Working Set'
where b.CategoryName = 'Process'
Result
This will execute.
Select * from (SELECT ROW_NUMBER() OVER(PARTITION BY LoadTestRunId ORDER BY LoadTestRunId DESC) as row,*
FROM [dbo].[LoadTest]) t1 where row=1
with your where clause
Select * from (SELECT ROW_NUMBER() OVER(PARTITION BY LoadTestRunId ORDER BY LoadTestRunId DESC),*
FROM [dbo].[LoadTest]) t1 where t1=1
and [LoadTestRunId] = '11180' and [CategoryName] = 'Process' and [InstanceName] like 'w3wp%'

Access 2010 - optimization a query

Can help me please to optimize this query in database (access 2010), this query to work very slowly (if use it in a big table):
SELECT П1.Code, П1.Field, П1.Number, П1.Data, [П1].[Number]-(select П3.Number from [Table] as П3
where П3.Field = П1.Field
and П3.Data = (select Max(Data)
from [Table] as П2
where П2.Field = П1.Field and П1.Data > П2.Data)) AS Difference
FROM [Table] AS П1
ORDER BY П1.Field, П1.Data;
I'm attach a picture: http://s33.postimg.org/otm859xtb/Table_query.png
Link in the database: http://s000.tinyupload.com/?file_id=06711692152703646964
How about...
SELECT t.Code,t.Field,t.Number,t.Data,t.Number-tm.LastNumber AS Difference
FROM [Table] AS t
INNER JOIN (
SELECT t.Field,t.Number AS LastNumber
FROM [Table] AS t
INNER JOIN (
SELECT Field,MAX(Data) AS MaxData
FROM [Table]
GROUP BY Field
) AS tm ON tm.Field=t.Field AND tm.MaxData=t.Data
) AS tm ON tm.Field=t.Field
The sub-selects can give you some issues with formatting in Access, but should work.
PLease try this one, just the same like Kevin ))
SELECT Table.Code, Table.Field, Table.Number, Table.Data, [Table].[Number]-[t1].[number] AS Difference
FROM
(SELECT Table.Code, Table.Field, Table.Number, Table.Data
FROM [Table] INNER JOIN
(SELECT Table.Field, Max(Table.Data) AS MaxOfData
FROM [Table] GROUP BY Table.Field) AS t2 ON (t2.MaxOfData = Table.Data) AND
(Table.Field = t2.Field)) AS t1 INNER JOIN [Table] ON t1.Field = Table.Field;

SQL Query behavior

I'm bogged in trying to figure out why query a is returning different records than query b. Both queries have seemingly same purpose yet a is returning 500 and b 3500.
this is query a:
SELECT DISTINCT ODE.OrderBillToID
FROM APTIFY.dbo.vwVwOrderDetailsKGExtended ODE
WHERE ProductID IN (2022, 1393)
AND LTRIM(RTRIM(ODE.OrderStatus)) <> 'Cancelled'
AND LTRIM(RTRIM(ODE.OrderType)) <> 'Cancellation'
AND LTRIM(RTRIM(ODE.cancellationStatus)) <> 'FULLY CANCELLED'
UNION
SELECT DISTINCT ID
FROM APTIFY.dbo.vwPersons WHERE City = 'A'
UNION
SELECT DISTINCT RecordID
FROM APTIFY.dbo.vwTopicCodeLinks WHERE TopicCodeID = 16 AND Value = 'Yes, Please'
query b:
SELECT
APTIFY..vwPersons.ID
FROM
APTIFY..vwPersons
WHERE
( APTIFY..vwPersons.ID IN (
SELECT
vwMeetingRegistrants.ID
FROM
APTIFY.dbo.vwMeetings vwMeetings
INNER JOIN APTIFY.dbo.vwMeetingRegistrants vwMeetingRegistrants
ON vwMeetings.ID=vwMeetingRegistrants.ActualMeetingID WHERE
vwMeetings.ProductID = 2022
)
OR
APTIFY..vwPersons.ID IN (
SELECT
vwMeetingRegistrants.ID
FROM
APTIFY.dbo.vwMeetings vwMeetings
INNER JOIN APTIFY.dbo.vwMeetingRegistrants vwMeetingRegistrants
ON vwMeetings.ID=vwMeetingRegistrants.ActualMeetingID WHERE
vwMeetings.ProductID = 1393
)
OR
APTIFY..vwPersons.City = N'Albany' )
OR
((
APTIFY..vwPersons.ID IN (
SELECT
RecordID
FROM
APTIFY.dbo.vwTopicCodeLinks vwTopicCodeLinks
WHERE
vwTopicCodeLinks.TopicCodeID = 16
)
AND
APTIFY..vwPersons.ID IN (
SELECT
RecordID
FROM
APTIFY.dbo.vwTopicCodeLinks vwTopicCodeLinks
WHERE
vwTopicCodeLinks.Value = N'Yes, Please'
) )
)
vwMeetingsRegistrants from the b query are producing the same records as orderkgdetailsextended from query. I cannot see ANY difference in those queries - which perhaps shows my lack of understanding the query behaviour.
BIG Thanks for any points guys! :)
As it came out, incorrectly structured query is a result of badly configured application, Aptify.

MySQL query error 1064 (syntax error)

I'm trying to make the following query work but it seems to contain an error that I can't find. The query in question is:
select
A.*,
SD.*
from
(
( select
V71.Sollevamento_idAttrezzatura,
V71.Num_id_ON,
V71.Affidato_INAIL,
V71.Esito_Verifica,
V71.Prima_Verifica,
V71.Sospensione,
V71.Data_Verbale,
V71.Scadenza,
CO.Nome,
CO.Cognome,
CO.CF,
V71.Costo,
V71.Sconto as ScontoVerbale,
V71.Maggiorazione as MaggiorazioneVerbale,
V71.Indirizzo,
V71.Comune,
V71.Cap,
V71.Provincia,
V71.Regione
from
Verbale_Art71 as V71
join Collaboratore as CO
on V71.Codice_Tecnico = CO.Codice_Collaboratore
where
V71.Data_Verbale >= '2014-01-01'
and V71.Data_Verbale <= '2014-12-31' ) as VC
join
( select
S.Natura,
S.Anno_Immatricolazione,
S.Codice_Attribuzione_Matricola,
S.Provincia_Immatricolazione,
S.Numero_Matricola,
S.idSpecifica,
S.N_Panieri_Idroestrattori,
S.Modello,
S.Numero_Fabbrica,
S.Anno_Costruzione,
S.Sconto as ScontoAttr,
S.Maggiorazione as MaggiorazioneAttr,
P71.Tipo_Attr,
S.Sede,
S.idAttrezzatura
from
Sollevamento as S
join Periodicita_Art71 as P71
on S.idPeriodicita = P71.idPeriodicita ) as SP
on VC.Sollevamento_idAttrezzatura = SP.idAttrezzatura
) as A
join
( select
D.Ragione_Sociale,
D.Indirizzo,
D.Cap,
D.Comune,
D.Provincia,
D.Regione,
D.CF as CF_Ditta,
D.P_IVA,
SC.idSede
from
Ditta as D
join Sede as SC
on SC.Ditta = D.idDitta ) as SD
on ATTR71.Sede = SD.idSede
MySQL notifies that the syntax error is near as A join (select D.Ragione_Sociale, D.Indirizzo, D.Cap, D.Comune, D.Provincia
Anyone can help me find it? I've been looking for it since early morning and I'm going nuts. Thank anyone that will help me in advance, Giacomo
You are missing a select clause
select A.*, SD.*
from
(/* You are missing a select * from here */
(
select ..
) as VC
join
Try with
select A.*, SD.*
from
(select * from
(
select V71.Sollevamento_idAttrezzatura, V71.Num_id_ON, V71.Affidato_INAIL, V71.Esito_Verifica, V71.Prima_Verifica, V71.Sospensione, V71.Data_Verbale, V71.Scadenza, CO.Nome, CO.Cognome, CO.CF, V71.Costo, V71.Sconto as ScontoVerbale, V71.Maggiorazione as MaggiorazioneVerbale, V71.Indirizzo, V71.Comune, V71.Cap, V71.Provincia, V71.Regione
from Verbale_Art71 as V71
join
Collaboratore as CO
on V71.Codice_Tecnico = CO.Codice_Collaboratore
where V71.Data_Verbale >= '2014-01-01' and V71.Data_Verbale <= '2014-12-31'
) as VC
join
(
select S.Natura, S.Anno_Immatricolazione, S.Codice_Attribuzione_Matricola, S.Provincia_Immatricolazione, S.Numero_Matricola, S.idSpecifica, S.N_Panieri_Idroestrattori, S.Modello, S.Numero_Fabbrica, S.Anno_Costruzione, S.Sconto as ScontoAttr, S.Maggiorazione as MaggiorazioneAttr, P71.Tipo_Attr, S.Sede, S.idAttrezzatura
from Sollevamento as S
join
Periodicita_Art71 as P71
on S.idPeriodicita = P71.idPeriodicita
) as SP
on VC.Sollevamento_idAttrezzatura = SP.idAttrezzatura
) as A
join
(
select D.Ragione_Sociale, D.Indirizzo, D.Cap, D.Comune, D.Provincia, D.Regione, D.CF as CF_Ditta, D.P_IVA, SC.idSede
from Ditta as D
join Sede as SC
on SC.Ditta = D.idDitta
) as SD
on ATTR71.Sede = SD.idSede
Your final alias
on ATTR71.Sede = SD.idSede
should be
on A.Sede = SD.idSede
You can see it easily once the formatting / readability is better. The "A" was the alias result of the first JOINs using the ATTR71 alias table... The last join was only to the "A" alias and not the ATTR71 table.