how to make insert into in select - postgresql

i want to use insert into in select like this :
INSERT INTO action_periodique (action_periodique_valeur_id, affaire_id , typetache_id , etattache_id , actionemail_id)
SELECT (
INSERT INTO action_periodique_valeur (nom , debut_rappel , fin_rappel , freq_rappel , champ_id , affaire_id)
SELECT nom , debut_rappel , fin_rappel , freq_rappel , champ_id , 430
FROM action_periodique_valeur
WHERE action_periodique.action_periodique_valeur_id = action_periodique_valeur.id
RETURNING id ),
430 , typetache_id , etattache_id ,
(INSERT INTO actionemail ( copiecarbone , destinataires , expediteur , message , repondrea , sujet)
SELECT copiecarbone , destinataires , expediteur , message , repondrea , sujet
FROM actionemail
WHERE action_periodique.actionemail_id = actionemail.id )
FROM action_periodique
where affaire_id = 170
it is possible ?

You provided next to none information about what you are trying to do.
But it seems to me that you are looking for a data modifying CTE.
Something like this:
with c1 as (
INSERT INTO action_periodique_valeur (nom , debut_rappel , fin_rappel , freq_rappel , champ_id , affaire_id)
SELECT nom , debut_rappel , fin_rappel , freq_rappel , champ_id , 430
FROM action_periodique_valeur
WHERE action_periodique.action_periodique_valeur_id = action_periodique_valeur.id
RETURNING id
, c2 as (
INSERT INTO actionemail ( copiecarbone , destinataires , expediteur , message , repondrea , sujet)
SELECT copiecarbone , destinataires , expediteur , message , repondrea , sujet
FROM actionemail
WHERE action_periodique.actionemail_id = actionemail.id
returning id
)
INSERT INTO action_periodique (action_periodique_valeur_id, affaire_id , typetache_id , etattache_id , actionemail_id)
SELECT (select id from c1),
430,
typetache_id,
etattache_id ,
(select id from c2)
FROM action_periodique
where affaire_id = 170;
If this is not what you want you need to be way more specific.

Related

Looking for ways to optimize DB2 query

I have a DB2 query as below. I am looking for ways to improve the speed of this one. I have tried visual explain but no indexes were advised by the index advisor. Can somebody have a look at this and advise if something can be done?
There is
CREATE OR REPLACE VIEW PSCMPORDVW
AS
WITH INPROGRESS AS
(
SELECT
DIODR#
, DIDISP
, DIUNIT
, DISTST
, DIAPRV
, DIETAD
, DITRLR AS TRAILER_ID
, DIDR1
, DIETAT
FROM
LOAD
WHERE
DIETAD <> 0
AND DIETAT <> '0000'
ORDER BY
1
)
, STOPGROUP AS
(
SELECT
SOORD STOPORDER
, COUNT(*) STOPSREMAIN
, MIN(SOSTP#) NEXTSTOP
, MAX(SOAPPR) APPTREQ
FROM
STOPOFF
INNER JOIN
INPROGRESS
ON
DIODR# = SOORD
WHERE
SOARDT = 0
GROUP BY
SOORD
ORDER BY
1
)
, STOPAPPTS AS
(
SELECT
SOORD APPTORDER
, SOCUST STOPCUST
, SOEDA ETADATE
, SOETA ETATIME
, SOADT1 EARLYDATE
, SOATM1 EARLYTIME
, SOADT2 LATEDATE
, SOATM2 LATETIME
, SOCTYC NEXTCITY
, SOSTP# APPTSTOP
, SOST NEXTSTATE
FROM
STOPOFF
INNER JOIN
STOPGROUP
ON
STOPORDER = SOORD
AND NEXTSTOP = SOSTP#
)
SELECT
ORDER_NUMBER
, SHIPPER_ID
, SHIPPER_NAME
, SHIPPER_ADDRESS_1
, SHIPPER_ADDRESS_2
, SHIPPER_CITY
, SHIPPER_ST
, SHIPPER_ZIP
, SHIPPER_ZIP_EXT
, LOAD_AT_ID
, LOAD_AT_NAME
, LOAD_AT_ADDRESS_1
, LOAD_AT_ADDRESS_2
, LOAD_AT_CITY
, LOAD_AT_ST
, LOAD_AT_ZIP
, LOAD_AT_ZIP_EXT
, LOAD_AT_LATITUDE
, LOAD_AT_LONGITUDE
, EARLY_PU_DATE_TIME
, LATE_PU_DATE_TIME
, EARLY_DELV_DATE_TIME
, EST_REVENUE
, ORDER_DIV
, CONSIGNEE_ID
, CONSIGNEE_NAME
, CONSIGNEE_ADDRESS_1
, CONSIGNEE_ADDRESS_2
, CONSIGNEE_CITY
, CONSIGNEE_ST
, CONSIGNEE_ZIP
, CONSIGNEE_ZIP_EXT
, CONSIGNEE_LATITUDE
, CONSIGNEE_LONGITUDE
, TRAILER_TYPE
, ORDER_MESSAGE
, ADDITIONAL_STOPS
, CMDTY_CODE
, CMDTY_DESCRIPTION
, ORDER_MILES
, ORDER_WGT
, ORIGIN_CITY_CODE
, ORIGIN_CITY
, ORIGIN_ST
, DEST_CITY_CODE
, DEST_CITY_NAME
, DEST_ST
, PICK_UP_AREA
, PLAN_INFO
, NUMBER_LDS
, NUMBER_DISP
, SHIP_DATE_TIME
, NEW_PICKUP_AREA
, EQUIPMENT_NUMBER
, APPT_REQ
, APPT_MADE
, PRE_T_SEQ
, PRE_T_AREA
, LOAD_DISPATCHED
, CUST_SERV_REP
, NEGOTIATIONS
,
(
CASE
WHEN UNUNIT IS NOT NULL
THEN UNUNIT
ELSE ' '
END
)
UNIT_DISPATCHED
,
(
CASE
WHEN UNSUPR IS NOT NULL
THEN UNSUPR
ELSE ' '
END
)
DRIVER_MGR_CODE
, COALESCE(SUPNAM, ' ') DRIVER_MGR_NAME
,
(
CASE
WHEN UNFMGR IS NOT NULL
THEN UNFMGR
ELSE ' '
END
)
FLEET_MGR_CODE
, COALESCE(FLTNAM, ' ') FLEET_MGR_NAME
,
(
CASE
WHEN UNTRL1 IS NOT NULL
THEN UNTRL1
ELSE ' '
END
)
TRAILER_ID
, DIDISP DISPATCH_NUMBER
, (COALESCE(BCMCNEW, ' ')) FED_MC_ID
, DIUNIT DISPATCHED_UNIT
, CASE
WHEN UNETAD <> 0
AND UNETAT = ''
THEN CVTDATETIM(CHAR(UNETAD),'0000', (
SELECT
SUBSTR(DATA_AREA_VALUE, 1109, 2) AS TIMEZONE
FROM
TABLE(QSYS2.DATA_AREA_INFO('COMPAN', '*LIBL'))
)
)
WHEN UNETAD <> 0
THEN CVTDATETIM(CHAR(UNETAD),UNETAT, (
SELECT
SUBSTR(DATA_AREA_VALUE, 1109, 2) AS TIMEZONE
FROM
TABLE(QSYS2.DATA_AREA_INFO('COMPAN', '*LIBL'))
)
)
WHEN UNETAD = 0
THEN '0000-00-00T00:00:00-00:00'
END AS ETA_DATE_TIME
, NEXTSTOP
, CASE
WHEN SOARDT <> 0
AND SOARTM = ''
THEN CVTDATETIM(CHAR(SOARDT),'0000', (
SELECT
SUBSTR(DATA_AREA_VALUE, 1109, 2) AS TIMEZONE
FROM
TABLE(QSYS2.DATA_AREA_INFO('COMPAN', '*LIBL'))
)
)
WHEN SOARDT <> 0
THEN CVTDATETIM(CHAR(SOARDT),SOARTM, (
SELECT
SUBSTR(DATA_AREA_VALUE, 1109, 2) AS TIMEZONE
FROM
TABLE(QSYS2.DATA_AREA_INFO('COMPAN', '*LIBL'))
)
)
WHEN SOARDT = 0
THEN '0000-00-00T00:00:00-00:00'
END AS STOP_ARRIVAL_DATE_TIME
, CASE
WHEN SOLUDT <> 0
AND SOLUTM = ''
THEN CVTDATETIM(CHAR(SOLUDT),'0000', (
SELECT
SUBSTR(DATA_AREA_VALUE, 1109, 2) AS TIMEZONE
FROM
TABLE(QSYS2.DATA_AREA_INFO('COMPAN', '*LIBL'))
)
)
WHEN SOLUDT <> 0
THEN CVTDATETIM(CHAR(SOLUDT),SOLUTM, (
SELECT
SUBSTR(DATA_AREA_VALUE, 1109, 2) AS TIMEZONE
FROM
TABLE(QSYS2.DATA_AREA_INFO('COMPAN', '*LIBL'))
)
)
WHEN SOLUDT = 0
THEN '0000-00-00T00:00:00-00:00'
END AS STOP_DEPART_DATE_TIME
, ORBAMT ORDER_INV_AMT
, ORARST AR_STATUS_FLAG
, DISTST SETTLEMENT_FLAG
, DIAPRV APPROVED_FOR_PAY
, BCCARR CARRIER_CODE
, BCNAME CARRIER_NAME
, BCADDR CARRIER_ADDRESS_1
, BCADR2 CARRIER_ADDRESS_2
, BCCITY CARRIER_CITY
, BCST CARRIER_ST
, BCZIP CARRIER_ZIP
FROM
INPROGRESS
INNER JOIN
PSMAINORVW A
ON
DIODR# = ORDER_NUMBER
AND DIDISP = NUMBER_DISP
AND
(
SUBSTR(ORDER_NUMBER, 1, 2) <> 'DH'
AND SUBSTR(ORDER_NUMBER, 1, 1) <> 'M'
)
LEFT OUTER JOIN
STOPOFF
ON
DIODR# = SOORD
AND SOSTP# = 90
LEFT OUTER JOIN
LMCARR
ON
DIUNIT = BCCARR
LEFT OUTER JOIN
MMILES
ON
MMORD# = DIODR#
AND MMRECTYPE = 'D'
AND MMDSP# = DIDISP
EXCEPTION JOIN
ORDBILL B
ON
B.ORODR# = DIODR#
AND B.ORSEQ = ' '
AND ORARST = '1'
LEFT OUTER JOIN
STOPGROUP
ON
STOPORDER = DIODR#
LEFT OUTER JOIN
STOPAPPTS
ON
APPTORDER = STOPORDER
AND APPTSTOP = NEXTSTOP
LEFT OUTER JOIN
UNITS
ON
UNUNIT = DIUNIT
AND UNORD# = ORDER_NUMBER
LEFT OUTER JOIN
SUPMAST
ON
SUPCDE = UNSUPR
LEFT OUTER JOIN
FLTMAST
ON
UNFMGR = FLTCDE
WHERE
DIETAD <> 0
AND DIETAT <> '0000'
RCDFMT PSCMPORDVW ;
I suspect that the below part might be slowing it up. Can someone advise what can be done here?
STOPGROUP AS
(
SELECT
SOORD STOPORDER
, COUNT(*) STOPSREMAIN
, MIN(SOSTP#) NEXTSTOP
, MAX(SOAPPR) APPTREQ
FROM
STOPOFF
INNER JOIN
INPROGRESS
ON
DIODR# = SOORD
WHERE
SOARDT = 0
GROUP BY
SOORD
ORDER BY
1
)
Even though Visual Explain (VE) doesn't advise any indexes ... it can still be used to see how long various parts of your query are taking.
If the
SELECT
SOORD STOPORDER
, COUNT(*) STOPSREMAIN
, MIN(SOSTP#) NEXTSTOP
, MAX(SOAPPR) APPTREQ
Turns out to really be any issue, I'd look at using an Encoded Vector Index (EVI) with aggregate values to speed that up.
I'd suggest breaking it down and building back up while using VE to see where the issues lie.
The only magic wand I might suggest is putting code into a user defined table function (UDTF); assuming you currently plan to use the view like so:
select *
from myview
where something = 'somevalue';
A UDTF would allow for you to explicitly push the selection into the query
select *
from table ( myudtf('somevalue'));

The error message is [Amazon](500310) Invalid operation: This type of correlated subquery pattern is not supported due to internal error

This is the query
CREATE TABLE dw_prestage.check_fact_update
AS
SELECT transaction_id,
transaction_line_id,
subsidiary_id
FROM ( SELECT transaction_id,
transaction_line_id,
subsidiary_id
FROM( SELECT
document_number ,
transaction_number ,
transaction_id ,
transaction_line_id ,
transaction_order ,
custom_form_id ,
document_status ,
transaction_type ,
currency_id ,
trandate ,
exchange_rate ,
account_id ,
amount ,
amount_foreign ,
gross_amount ,
net_amount ,
net_amount_foreign ,
quantity ,
item_id ,
item_unit_price ,
tax_item_id ,
tax_amount ,
location_id ,
class_id ,
subsidiary_id ,
accounting_period_id ,
check_id ,
check_type ,
created_by_id ,
create_date ,
date_last_modified ,
trx_type ,
memo
FROM dw_prestage.check_fact a2
WHERE NOT EXISTS ( SELECT 1 FROM dw_prestage.check_fact_insert b2
WHERE b2.transaction_id = a2.transaction_id
AND b2.transaction_line_id = a2.transaction_line_id
AND a2.subsidiary_id = b2.subsidiary_id
)
MINUS
SELECT
document_number ,
transaction_number ,
transaction_id ,
transaction_line_id ,
transaction_order ,
custom_form_id ,
document_status ,
transaction_type ,
currency_id ,
trandate ,
exchange_rate ,
account_id ,
amount ,
amount_foreign ,
gross_amount ,
net_amount ,
net_amount_foreign ,
quantity ,
item_id ,
item_unit_price ,
tax_item_id ,
tax_amount ,
location_id ,
class_id ,
subsidiary_id ,
accounting_period_id ,
check_id ,
check_type ,
created_by_id ,
create_date ,
date_last_modified ,
trx_type ,
memo
FROM dw_stage.check_fact a1
WHERE EXISTS ( SELECT 1 FROM dw_prestage.check_fact b1
WHERE b1.transaction_id = a1.transaction_id
AND b1.transaction_line_id = a1.transaction_line_id
AND a1.subsidiary_id = b1.subsidiary_id
)
)
) a
WHERE NOT EXISTS (SELECT 1
FROM dw_prestage.check_fact_insert aa
WHERE aa.transaction_id = a.transaction_id
AND aa.transaction_line_id = a.transaction_line_id);
plz suggest any alternative way to replace this query.
The error is because the queries in your NOT EXISTS clauses reference a table outside of the of the clause. Convert the NOT EXISTS clause into a LEFT JOIN with a predicate to exclude any matches. This pattern is often called an "anti-join".
Current:
FROM (…) a
WHERE NOT EXISTS (SELECT 1
FROM dw_prestage.check_fact_insert aa
WHERE aa.transaction_id = a.transaction_id
AND aa.transaction_line_id = a.transaction_line_id)
Rewrite:
FROM (…) a
LEFT JOIN dw_prestage.check_fact_insert aa
ON a.transaction_id = aa.transaction_id
AND a.transaction_line_id = aa.transaction_line_id
WHERE aa.transaction_id IS NULL

Pivot With Grouping?

I am building a query for a SSRS Report and I have a pivot for locations and quantity. I am getting two rows one for each location but when I pivot I want the end result to be one row.
SELECT *
FROM ( SELECT DISTINCT ItemNmbr ,
ITEMDESC ,
Location ,
QtyOnhand ,
QtyOnOrder ,
QtyBackordered ,
TotalInventory ,
EXTDCOST ,
InventoryValue
FROM #ssrsFinal
) AS p PIVOT
(SUM(QTYOnHand) FOR Location IN ( Loc1, Loc2, HUB, INLAND, Loc, [OLD Loc],[IN TRANSIT] )
) AS pvt;
My result is two rows, How do i get it to just one?
I have tried inserting the pivot results into a temp table and then grouping but it does not carry over the locations in the select.
Results before the Pivot. 3 Different Locations.
I think this is what you are looking for:
You have already made the pivot, you just need to aggregate the result of the pivot table accordingly.
Assumption: Grouping by ItemNmbr,ITEMDESC,EXTDCOST,Loc1,Loc2,HUB,INLAND,Loc,[OLD
Loc],[IN TRANSIT]
SELECT ItemNmbr ,
ITEMDESC ,
QtyOnOrder=SUM(QtyOnOrder) ,
QtyBackordered=SUM(QtyBackordered) ,
TotalInventory=SUM(TotalInventory) ,
EXTDCOST,
InventoryValue = SUM(InventoryValue) ,
Loc1,
Loc2,
HUB,
INLAND,
Loc,
[OLD Loc],
[IN TRANSIT]
FROM ( SELECT DISTINCT ItemNmbr ,
ITEMDESC ,
Location ,
QtyOnhand ,
QtyOnOrder ,
QtyBackordered ,
TotalInventory ,
EXTDCOST ,
InventoryValue
FROM #ssrsFinal
) AS p PIVOT
(SUM(QTYOnHand) FOR Location IN ( Loc1, Loc2, HUB, INLAND, Loc, [OLD Loc],[IN TRANSIT] )
) AS pvt
GROUP BY ItemNmbr ,
ITEMDESC ,
EXTDCOST,
Loc1,
Loc2,
HUB,
INLAND,
Loc,
[OLD Loc],
[IN TRANSIT] ;
In Response to the comment:
Sample data set:
CREATE TABLE #ssrsFinal (ItemNmbr VARCHAR(10),
ITEMDESC VARCHAR(100),
Location VARCHAR(10),
QtyOnhand INT,
QtyOnOrder INT,
QtyBackordered INT,
TotalInventory INT,
EXTDCOST DECIMAL(20,5),
InventoryValue DECIMAL(20,2))
INSERT INTO #ssrsFinal
VALUES
('94185BJGD','SS MESH ROAST PAN, 2X GRILL CLAWS, STAM HNDL, GD','Something',0,0,0,0,14.18000,0),
('94185BJGD','SS MESH ROAST PAN, 2X GRILL CLAWS, STAM HNDL, GD','Something',0,0,0,0,14.18000,0),
('94185BJGD','SS MESH ROAST PAN, 2X GRILL CLAWS, STAM HNDL, GD','Something',3,0,0,3,14.18000,42.54)
In response to the comment "...insert values instead of "something" for location try adding a different location from the examples and then run your query again, it will pull back two rows. I tried INLAND, HUB, and LOC.":
SELECT ItemNmbr ,
ITEMDESC ,
QtyOnOrder=SUM(QtyOnOrder) ,
QtyBackordered=SUM(QtyBackordered) ,
TotalInventory=SUM(TotalInventory) ,
EXTDCOST,
InventoryValue = SUM(InventoryValue) ,
Loc1=SUM(Loc1),
Loc2=SUM(Loc2),
HUB=SUM(HUB),
INLAND=SUM(INLAND),
Loc=SUM(Loc),
[OLD Loc]=SUM([OLD Loc]),
[IN TRANSIT]=SUM([IN TRANSIT])
FROM ( SELECT DISTINCT ItemNmbr ,
ITEMDESC ,
Location ,
QtyOnhand ,
QtyOnOrder ,
QtyBackordered ,
TotalInventory ,
EXTDCOST ,
InventoryValue
FROM #ssrsFinal
) AS p PIVOT
(SUM(QTYOnHand) FOR Location IN ( Loc1, Loc2, HUB, INLAND, Loc, [OLD Loc],[IN TRANSIT] )
) AS pvt
GROUP BY ItemNmbr ,
ITEMDESC ,
EXTDCOST ;
Results:

How to order UNPIVOT

I have the following UNPIVOT code and I would like to order it by the FactSheetSummary columns so that when it is converted to rows it is order 1 - 12:
INSERT INTO #Results
SELECT DISTINCT ReportingDate, PortfolioID,ISIN, PortfolioNme, Section,REPLACE(REPLACE(Risks,'‘',''''),'’','''')
FROM
(SELECT DISTINCT
ReportingDate
, PortfolioID
, ISIN
, PortfolioNme
, Section
, FactSheetSummary_1, FactSheetSummary_2, FactSheetSummary_3
, FactSheetSummary_4, FactSheetSummary_5, FactSheetSummary_6
, FactSheetSummary_7, FactSheetSummary_8, FactSheetSummary_9
, FactSheetSummary_10, FactSheetSummary_11, FactSheetSummary_12
FROM #WorkingTableFactsheet) p
UNPIVOT
(Risks FOR FactsheetSummary IN
( FactSheetSummary_1, FactSheetSummary_2, FactSheetSummary_3
, FactSheetSummary_4, FactSheetSummary_5, FactSheetSummary_6
, FactSheetSummary_7, FactSheetSummary_8, FactSheetSummary_9
, FactSheetSummary_10, FactSheetSummary_11, FactSheetSummary_12)
)AS unpvt;
--DELETE records where there are no Risk Narratives
DELETE FROM #Results
WHERE Risks = ''
SELECT
ReportingDate
, PortfolioID
, ISIN
, PortfolioNme
, Section
, Risks
, ROW_NUMBER() OVER(PARTITION BY ISIN,Section ORDER BY ISIN,Section,Risks) as SortOrder
FROM #Results
order by ISIN, Risks
Is it possible to do this? I thought the IN of the UNPIVOT would dictate the order? Do I need to add a column to dictate which I would like to be 1 through to 12?
Just use case expression to order:
order by case FactsheetSummary
when 'FactSheetSummary_1' then 1
when 'FactSheetSummary_2' then 2
when 'FactSheetSummary_12' then 12 end

How to get the rows position numbers of a table result

This is my code
Select #pos = Pos, #ptsReputacion = isnull(AA.PtsReputacion,0)
From
(Select
ROW_NUMBER() OVER (ORDER BY #ptsReputacion DESC) AS Pos
, USUARIO.CodUsuario
, PtsReputacion = (Select isnull(sum(Puntos),0) as Puntos
From USUARIO_RANKING_INTERES
Where USUARIO_RANKING_INTERES.CodUsuario = #codUsuario)
, USUARIO.CantIntentos as Intentos
, USUARIO.CantAciertos as Aciertos
, USUARIO.CantFallos as Fallos
, isnull(USUARIO.PG,0) as PG
, isnull(USUARIO.PE,0) as PE
, isnull(USUARIO.PP,0) as PP
, isnull(USUARIO.TiempoTotal,0) as TiempoTotal
From USUARIO) AA
Where AA.CodUsuario = #codUsuario
But it doesn't works because the Pos field has an other value. For example, it gives 2 instead 1.
I want to know how to get the row position number one by one ordered by a variable (because the field is a subquery).
It looks like you really want to do something like the below. I'm using CTEs because that makes it easier to read.
WITH BaseQuery AS
(
SELECT
U.CodUsuario
, PtsReputacion = (Select isnull(sum(Puntos),0) as Puntos
From USUARIO_RANKING_INTERES
Where USUARIO_RANKING_INTERES.CodUsuario = U.CodUsuario)
, USUARIO.CantIntentos as Intentos
, USUARIO.CantAciertos as Aciertos
, USUARIO.CantFallos as Fallos
, isnull(USUARIO.PG,0) as PG
, isnull(USUARIO.PE,0) as PE
, isnull(USUARIO.PP,0) as PP
, isnull(USUARIO.TiempoTotal,0) as TiempoTotal
FROM USUARIO U
),
RNQuery AS
(
SELECT
*
, ROW_NUMBER() OVER (ORDER BY PtsReputacion DESC) AS Pos
FROM
BaseQuery
)
SELECT
#pos = Pos
, #ptsReputacion = isnull(AA.PtsReputacion,0)
FROM
RNQuery AS AA
WHERE
AA.CodUsuario = #codUsuario