SELECT
obj.obj_id obj_id,
obj.obj_nm obj_nm,
objsecu.usr_id usr_id,
objsecu.email_id email_id,
dbo.NVL(objprop.prop_val,'MM/DD/YYYY') prop_val
FROM
od_mdv_actual_obj obj,
od_md_objsecu objsecu,
od_mdv_objprop objprop
WHERE
obj.obj_id = objsecu.obj_id
AND obj.clnt_id = objsecu.clnt_id
AND obj.proj_id = objsecu.proj_id
AND obj.schm_id = objsecu.schm_id
AND obj.obj_id = objprop.obj_id (+)
AND obj.clnt_id = objprop.clnt_id (+)
AND obj.proj_id = objprop.proj_id (+)
AND obj.schm_id = objprop.schm_id (+)
AND 2007 = objprop.prop_id (+)
AND obj.clnt_id =1
AND obj.proj_id =1
AND obj.schm_id =1
AND obj.obj_id IN (
SELECT
obj_depn_id
FROM
od_md_objrel
WHERE
rel_typ_id = 19
AND clnt_id =1
AND proj_id =1
AND schm_id =1
);
I am trying to fetch user list using the above query dbo.NVL failing and showing error as "Incorrect syntax near ')'. " How to fix it? Please help me
You are getting the Error because of the (+) symbols.
AND obj.obj_id = objprop.obj_id (+)
AND obj.clnt_id = objprop.clnt_id (+)
AND obj.proj_id = objprop.proj_id (+)
AND obj.schm_id = objprop.schm_id (+)
AND 2007 = objprop.prop_id (+)
Remove that (+), and it will work fine.
As per the comment , you are looking to Left join..
SELECT
obj.obj_id obj_id,
obj.obj_nm obj_nm,
objsecu.usr_id usr_id,
objsecu.email_id email_id,
dbo.NVL(objprop.prop_val,'MM/DD/YYYY') prop_val
FROM od_mdv_actual_obj obj
left join od_md_objsecu objsecu on obj.obj_id = objsecu.obj_id
AND obj.clnt_id = objsecu.clnt_id
AND obj.proj_id = objsecu.proj_id
AND obj.schm_id = objsecu.schm_id
left join od_mdv_objprop objprop on obj.obj_id = objprop.obj_id
AND obj.clnt_id = objprop.clnt_id
AND obj.proj_id = objprop.proj_id
AND obj.schm_id = objprop.schm_id
WHERE objprop.prop_id =2007
AND obj.clnt_id =1
AND obj.proj_id =1
AND obj.schm_id =1
AND obj.obj_id IN (
SELECT
obj_depn_id
FROM
od_md_objrel
WHERE
rel_typ_id = 19
AND clnt_id =1
AND proj_id =1
AND schm_id =1
);
Related
**The below query is working badly, and I'm planning to replace case stmt in where clause with temp table. Pls suggest to me some option to rewrite this query
Is there a way to simplify this into multiple SQLs
Also explain me how this case stmt works in where clause**
select DISTINCT
ph.order_type_cd,
c.order_num,
ph.created_date,
os.order_status_desc,
ph.facility_name,
PH.vendor_order_num,
l.lic_nm,
(u.last_nm + ', ' + u.first_nm )as requestor_nm,
bl.billing_location_desc,
ph.ship_to_name,
dm.dispatch_method_name_desc as courier,
PH.po_last_updated_dt as last_updated_date,
(u1.last_nm + ', ' + u1.first_nm )as last_updated_by,
ph.right_grp_id,
c.line_id,
a.material_product_id,
a.parent_material_product_id
from avt_po_detail c
inner join avt_po_hdr ph on ph.order_num = c.order_num
left outer join avt_material_product AS a on a.material_product_id=c.material_product_id
INNER JOIN #entity_ids po on po.entity_id = c.order_num --or #select_pos = 0 )
LEFT OUTER JOIN dbo.ert_product AS pc ON pc.product_id = a.product_id
left outer join ert_product_type as pt on pt.product_type_cd = pc.product_type_cd
LEFT OUTER JOIN dbo.ert_product_xref as xref on xref.product_id = a.parent_product_id AND xref.version_id = 1
left outer join avt_order_status AS OS ON OS.order_status_cd = PH.order_status_cd
left outer join avt_licensee l on l.lic_id = ph.lic_id
left outer join avt_po_from pf on pf.material_product_id = a.material_product_id and pf.line_id = c.line_id
left outer join avt_po_audio_detail pad on pad.line_id = c.line_id
left outer join avt_materials_trans_material MTM on mtm.sequence_no = c.video_seq_no
left outer join avt_user u on u.userid = ph.requestor_id
left outer join avt_user u1 on u1.userid = ph.po_last_updated_by
left outer join avt_billing_location bl on bl.billing_location_cd = PH.billing_location_cd
left outer join avt_dispatch_method_name dm on dm.dispatch_method_name_id = PH.dispatch_method_name_id
left outer join avt_right_group arg on arg.right_grp_id = ph.right_grp_id
left outer join #prod product on product.product_id=a.product_id and (product.version_id=c.dist_version_id OR product.version_id = 1)
where (pf.from_desc in ( select from_desc from #from_desc ) or #select_form = 0)
and (case WHEN c.dist_version_id IS NULL THEN c.UCS_prod_no
ELSE
CASE
WHEN isnull(pt.version_control_ind, 'N') = 'Y' THEN xref.rss_prod_no
WHEN
isnull(pt.version_control_ind, 'N') = 'N' AND
xref.rss_prod_no IS NULL AND
xref.rss_film_id IS NULL THEN xref.rss_titleid
WHEN
isnull(pt.version_control_ind, 'N') = 'N' AND
xref.rss_prod_no IS NOT NULL AND
xref.rss_film_id IS NULL THEN substring(pc.glacct, 24, 5) -- ASR 3290687
WHEN isnull(pt.version_control_ind, 'N') = 'N' AND xref.rss_film_id IS NOT NULL THEN isnull(substring(pc.glacct, 24, 5), -- ASR 3290687
(
SELECT substring(dbo.ert_product.glacct, 24, 5) -- ASR 3290687
FROM dbo.ert_product
WHERE dbo.ert_product.product_id = a.parent_product_id
))
END
END in (select prod_no from #prod_no) or #prod_no = 0)
I've been tasked to create a Powershell script that will create the following view which works currently within Microsoft SQL Studio. I've made a copy of the working script and would like to to apply it to this Microsoft example. My question is - can you take the known working query below and insert it in the TextBody property below?
# Set the TextHeader and TextBody property to define the view.
$myview.TextHeader = "CREATE VIEW [Sales].[Test_View] AS"
$myview.TextBody ="SELECT h.SalesOrderID, d.OrderQty FROM
Sales.SalesOrderHeader AS h INNER JOIN Sales.SalesOrderDetail AS d ON
h.SalesOrderID = d.SalesOrderID"
CREATE VIEW [dbo].[PROV] AS
SELECT drname.dr_id, drname.create_dt, dr_fname, dr_iname, dr_lname,
drtitle, drsuffix, gender, birthdate, marital, ethnic, drname.email,
org_name, dr_ofname, dr_oiname, dr_olname, nationalid, drname.medicare,
drname.medicaid,
CASE
WHEN EXISTS(SELECT 1 FROM stfstatu act WHERE act.dr_id =
drname.dr_id AND fac_cd NOT IN('SMC','WAR','CCS') AND act.active123 IN
('1','3','N','G','6','S','U','CA','TPRO')) THEN 'Y'
ELSE 'N'
END as Active_Status,
a.sch_type as Addr_Type_sch_type, a.addr, a.addr2, a.city,
a.state, a.zip, a.phone, a.fax, a2.tax_id,
(select top 1 rtrim(d.dr_lname) from drname d join address aa
on d.dr_id = aa.dr_id join address2 aa2 on aa.link = aa2.l_address where
d.verfac = 1 and aa2.tax_id = a2.tax_id and drname.verfac = 0) as
Addr_DrPGp,
lan_tab.txt as lan_tab_txt, dr_lan.lan_cd as dr_lan_cd, CASE
WHEN dr_spec.specorder = 1 THEN dr_spec.specialty ELSE '' END as dr_spec,
CASE WHEN dr_spec.PrimSpec = 1 THEN 'P' ELSE '' END as PrimSpec, school.cd
as school_cd, school.txt as school_txt, educate.fdate as educate_fdate,
educate.sch_type, educ_arr.txt as school_type_txt, educate.degree,
educ_tab.txt
as degree_txt, educate.tdate as educate_tdate, CASE WHEN dr_spec.specorder =
1
THEN spec_tab.txt ELSE '' END as spec_Tab_txt,
CASE WHEN stfstatu.pcp_spec = 'B' then 'Yes' WHEN
stfstatu.pcp_spec = 'P' then 'Yes' ELSE 'No' END as PCP,
case when stfstatu.pcp_spec = 'B' then 'PCP and Specialist'
else case when stfstatu.pcp_spec = 'P' then 'PCP'
else case when stfstatu.pcp_spec = 'S' then
'Specialist'
else ''
END
END
END as PCPSpec, taxonomy.cd as tax_cd
FROM drname
JOIN stfstatu on drname.dr_id = stfstatu.dr_id
LEFT JOIN address1 a on drname.dr_id = a.dr_id AND a.sch_type = 'G' AND
a.link = (SELECT TOP 1 link FROM address1 WHERE sch_type = 'G' AND
address1.dr_id = drname.dr_id ORDER BY LINK DESC)
LEFT JOIN address2 a2 on a2.l_address = a.link
LEFT JOIN dr_lan on drname.dr_id = dr_lan.dr_id
LEFT JOIN lan_tab on lan_tab.cd = dr_lan.lan_cd
LEFT JOIN dr_spec on drname.dr_id = dr_spec.dr_id
LEFT JOIN spec_tab on dr_spec.specialty = spec_tab.cd
LEFT JOIN educate on educate.dr_id = drname.dr_id
LEFT JOIN school on educate.cd = school.cd
LEFT JOIN educ_arr on educ_arr.cd = educate.sch_type
LEFT JOIN facility on facility.fac_cd = educate.fac_cd
LEFT JOIN educ_tab on educate.degree = educ_tab.cd
LEFT JOIN taxonomy on taxonomy.dr_id = drname.dr_id
--Where LTRIM(RTRIM(dr_spec.Fac_Cd)) = ''
did you try using the here string (https://www.safaribooksonline.com/library/view/windows-powershell-cookbook/9780596528492/ch05s03.html]) for TextBody?
# Set the TextHeader and TextBody property to define the view.
$myview.TextHeader = "CREATE VIEW [Sales].[Test_View] AS"
$myview.TextBody = #"
SELECT h.SalesOrderID, d.OrderQty FROM
Sales.SalesOrderHeader AS h INNER JOIN Sales.SalesOrderDetail AS d ON
h.SalesOrderID = d.SalesOrderID
CREATE VIEW [dbo].[PROV] AS
SELECT drname.dr_id, drname.create_dt, dr_fname, dr_iname, dr_lname,
drtitle, drsuffix, gender, birthdate, marital, ethnic, drname.email,
org_name, dr_ofname, dr_oiname, dr_olname, nationalid, drname.medicare,
drname.medicaid,
CASE
WHEN EXISTS(SELECT 1 FROM stfstatu act WHERE act.dr_id =
drname.dr_id AND fac_cd NOT IN('SMC','WAR','CCS') AND act.active123 IN
('1','3','N','G','6','S','U','CA','TPRO')) THEN 'Y'
ELSE 'N'
END as Active_Status,
a.sch_type as Addr_Type_sch_type, a.addr, a.addr2, a.city,
a.state, a.zip, a.phone, a.fax, a2.tax_id,
(select top 1 rtrim(d.dr_lname) from drname d join address aa
on d.dr_id = aa.dr_id join address2 aa2 on aa.link = aa2.l_address where
d.verfac = 1 and aa2.tax_id = a2.tax_id and drname.verfac = 0) as
Addr_DrPGp,
lan_tab.txt as lan_tab_txt, dr_lan.lan_cd as dr_lan_cd, CASE
WHEN dr_spec.specorder = 1 THEN dr_spec.specialty ELSE '' END as dr_spec,
CASE WHEN dr_spec.PrimSpec = 1 THEN 'P' ELSE '' END as PrimSpec, school.cd
as school_cd, school.txt as school_txt, educate.fdate as educate_fdate,
educate.sch_type, educ_arr.txt as school_type_txt, educate.degree,
educ_tab.txt
as degree_txt, educate.tdate as educate_tdate, CASE WHEN dr_spec.specorder =
1
THEN spec_tab.txt ELSE '' END as spec_Tab_txt,
CASE WHEN stfstatu.pcp_spec = 'B' then 'Yes' WHEN
stfstatu.pcp_spec = 'P' then 'Yes' ELSE 'No' END as PCP,
case when stfstatu.pcp_spec = 'B' then 'PCP and Specialist'
else case when stfstatu.pcp_spec = 'P' then 'PCP'
else case when stfstatu.pcp_spec = 'S' then
'Specialist'
else ''
END
END
END as PCPSpec, taxonomy.cd as tax_cd
FROM drname
JOIN stfstatu on drname.dr_id = stfstatu.dr_id
LEFT JOIN address1 a on drname.dr_id = a.dr_id AND a.sch_type = 'G' AND
a.link = (SELECT TOP 1 link FROM address1 WHERE sch_type = 'G' AND
address1.dr_id = drname.dr_id ORDER BY LINK DESC)
LEFT JOIN address2 a2 on a2.l_address = a.link
LEFT JOIN dr_lan on drname.dr_id = dr_lan.dr_id
LEFT JOIN lan_tab on lan_tab.cd = dr_lan.lan_cd
LEFT JOIN dr_spec on drname.dr_id = dr_spec.dr_id
LEFT JOIN spec_tab on dr_spec.specialty = spec_tab.cd
LEFT JOIN educate on educate.dr_id = drname.dr_id
LEFT JOIN school on educate.cd = school.cd
LEFT JOIN educ_arr on educ_arr.cd = educate.sch_type
LEFT JOIN facility on facility.fac_cd = educate.fac_cd
LEFT JOIN educ_tab on educate.degree = educ_tab.cd
LEFT JOIN taxonomy on taxonomy.dr_id = drname.dr_id
--Where LTRIM(RTRIM(dr_spec.Fac_Cd)) = ''
"#
I have a string to replace with the expected form.
Input: I have the following string.
'A,B,C,D,E,F,G,H,I,J,K,L'
And I want to replace the above string into the following format:
'x.A = z.A ,
x.B = z.B ,
x.C = z.C ,
x.D = z.D ,
x.E = z.E ,
x.F = z.F ,
.........
.........
x.L = z.L'
My try:
SELECT 'x.'||REPLACE('A,B,C,D,E,F,G,H,I,J,K,L',',',' = z.')
SELECT 'x.' || col || '=z.' || col
FROM (
SELECT unnest(regexp_split_to_array('A,B,C,D,E,F,G,H,I,J,K,L', ',')) col
) t
You can use string_agg and FORMAT:
SELECT string_agg(FORMAT('x.%s = z.%s', t,t) , ',')
FROM (SELECT unnest(regexp_split_to_array('A,B,C,D,E,F,G,H,I,J,K,L', ',')) AS t
) AS sub;
You can use as delimeter E',\r\n' to get carriage return:
SELECT string_agg(FORMAT('x.%s = z.%s', t,t) , E',\r\n')
FROM (SELECT unnest(regexp_split_to_array('A,B,C,D,E,F,G,H,I,J,K,L', ',')) AS t)
AS sub
Output:
x.A = z.A,
x.B = z.B,
x.C = z.C,
x.D = z.D,
x.E = z.E,
x.F = z.F,
x.G = z.G,
x.H = z.H,
x.I = z.I,
x.J = z.J,
x.K = z.K,
x.L = z.L
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
I have select, iside select have 2 column. This column must be filled from same select, but I don't want use select twice for it. Is it possoble use select 1 time and after that set second column value from first?
Example:
insert into #temptable from
select
a = (select aa from table1 where quantity > 5)
b = (select aa from table1 where quantity > 5)
I need:
insert into #temptable from
select
a = (select aa from table1 where quantity > 5)
b = {value from a}
Update. I wrote bad example, I need set to BalancePrediction1 and BalancePrediction2 value from Balance
INSERT #tmpBalances
SELECT PA.ContractId AS 'ContractId',
Con.Name AS 'ContractName',
Bal.PortfolioAccountId AS 'PortfolioAccountId',
PA.Name AS 'PortfolioAccountName',
RA.GeneralId AS 'RegisterAccountGeneralId',
Bal.BalanceTypeId AS 'BalanceTypeId',
Bt.Name AS 'BalanceTypeName',
Bt.Type AS 'BalanceTypeType',
Bal.BalanceTimeType AS 'BalanceTimeType',
Bal.InstrumentId AS 'InstrumentId',
Ins.Name AS 'InstrumentName',
Ins.GeneralId AS 'InstrumentGeneralId',
(Bal.Balance -
(
SELECT COALESCE(SUM(Mov.Amount), 0)
FROM trd.Movements AS Mov
WHERE
Bal.InstrumentId = Mov.InstrumentId AND
Bal.PortfolioAccountId = Mov.PortfolioAccountId AND
Bal.BalanceTypeId = Mov.BalanceTypeId AND
Bal.BalanceTimeType = Mov.BalanceTimeType AND
DateDiff(DAY, #Date, Mov.Date) > 0 AND
-- Currency může být null a NULL = NULL nejde
COALESCE(Bal.CurrencyId, -1) = COALESCE(Mov.CurrencyId, -1)
)
) as Balance,
Balance AS 'BalancePrediction1',
Balance AS 'BalancePrediction2',
Bal.CurrencyId AS 'CurrencyId',
Ccy.Code AS 'CurrencyCode',
PA.PositionServiceType 'PositionServiceType',
Ccy.Name 'CurrencyName',
S.Nominal AS 'Nominal',
S.NominalCurrencyId AS 'NominalCurrencyId',
trd.GetCurrencyCode(S.NominalCurrencyId) AS 'NominalCurrencyCode'
FROM trd.Balances AS Bal
JOIN trd.PortfolioAccounts AS PA ON PA.Id = Bal.PortfolioAccountId
JOIN trd.Contracts AS Con ON Con.Id = PA.ContractId
JOIN trd.RegisterAccounts AS RA ON RA.Id = PA.RegisterAccountId
JOIN trd.BalanceTypes AS Bt ON Bt.Id = Bal.BalanceTypeId
JOIN trd.Instruments AS Ins ON Ins.Id = Bal.InstrumentId
LEFT OUTER JOIN trd.Currencies AS Ccy ON Ccy.Id = Bal.CurrencyId
LEFT JOIN trd.SecuritiesView S ON s.Id = Ins.Id AND DateDiff(d, S.ValidFrom, #Date) >= 0 AND (S.ValidTo IS NULL OR DateDiff(d, S.ValidTo, #Date) < 0)
AND S.InstrumentInstrumentTypePriceUnit = 1
You could do an update to the table variable after the insert.
update #tmpBalances
set BalancePrediction1 = Balance,
BalancePrediction2 = Balance
Or you can use cross apply to calculate the sum.
INSERT #tmpBalances
SELECT PA.ContractId AS 'ContractId',
Con.Name AS 'ContractName',
Bal.PortfolioAccountId AS 'PortfolioAccountId',
PA.Name AS 'PortfolioAccountName',
RA.GeneralId AS 'RegisterAccountGeneralId',
Bal.BalanceTypeId AS 'BalanceTypeId',
Bt.Name AS 'BalanceTypeName',
Bt.Type AS 'BalanceTypeType',
Bal.BalanceTimeType AS 'BalanceTimeType',
Bal.InstrumentId AS 'InstrumentId',
Ins.Name AS 'InstrumentName',
Ins.GeneralId AS 'InstrumentGeneralId',
(Bal.Balance - Mov.SumAmount) AS Balance,
(Bal.Balance - Mov.SumAmount) AS 'BalancePrediction1',
(Bal.Balance - Mov.SumAmount) AS 'BalancePrediction2',
Bal.CurrencyId AS 'CurrencyId',
Ccy.Code AS 'CurrencyCode',
PA.PositionServiceType 'PositionServiceType',
Ccy.Name 'CurrencyName',
S.Nominal AS 'Nominal',
S.NominalCurrencyId AS 'NominalCurrencyId',
trd.GetCurrencyCode(S.NominalCurrencyId) AS 'NominalCurrencyCode'
FROM trd.Balances AS Bal
JOIN trd.PortfolioAccounts AS PA ON PA.Id = Bal.PortfolioAccountId
JOIN trd.Contracts AS Con ON Con.Id = PA.ContractId
JOIN trd.RegisterAccounts AS RA ON RA.Id = PA.RegisterAccountId
JOIN trd.BalanceTypes AS Bt ON Bt.Id = Bal.BalanceTypeId
JOIN trd.Instruments AS Ins ON Ins.Id = Bal.InstrumentId
LEFT OUTER JOIN trd.Currencies AS Ccy ON Ccy.Id = Bal.CurrencyId
LEFT JOIN trd.SecuritiesView S ON s.Id = Ins.Id AND DateDiff(d, S.ValidFrom, #Date) >= 0 AND (S.ValidTo IS NULL OR DateDiff(d, S.ValidTo, #Date) < 0)
AND S.InstrumentInstrumentTypePriceUnit = 1
CROSS APPLY (SELECT COALESCE(SUM(Mov.Amount), 0)
FROM trd.Movements AS Mov
WHERE
Bal.InstrumentId = Mov.InstrumentId AND
Bal.PortfolioAccountId = Mov.PortfolioAccountId AND
Bal.BalanceTypeId = Mov.BalanceTypeId AND
Bal.BalanceTimeType = Mov.BalanceTimeType AND
DateDiff(DAY, #Date, Mov.Date) > 0 AND
-- Currency může být null a NULL = NULL nejde
COALESCE(Bal.CurrencyId, -1) = COALESCE(Mov.CurrencyId, -1)
) Mov(SumAmount)
SELECT aa AS a, aa AS b
FROM table1
WHERE quantity > 5
One way;
;with T (value) as (
select aa from table1 where quantity > 5
)
insert into #temptable
select value, value from T