troubles with error: Divide by zero error encountered - sql

Hello two days I have tried to figure out why my code isn't working.
I am quite sure that it's a stupid mistake, but if anybody has time to check the code I would really appreciate.
I have tried to comment out this "SUM" case, but then everything else breaks
I know that this line screws with me, but I can't figure out how to fix this:
sum (Case when bm.CaseQTY IS NULL
then (k.postedqty / mm.CaseQTY)
else (k.postedqty / bm.CaseQTY)
End) as laoseiskaste,
sum (Case when bm.CaseQTY IS NULL
then ((k.postedqty-k.reservordered-k.reservphysical-k.picked+k.registered) / mm.CaseQTY)
else ((k.postedqty-k.reservordered-k.reservphysical-k.picked+k.registered) / bm.CaseQTY)
End) as vabakaste
from (select s.itemid, i.product, i.ItemMiscRefId, i.MMFItemProductGroupId, s.INVENTDIMID,
s.postedqty, s.registered, s.reservordered, s.reservphysical, s.picked, s.ordered,
s.postedvalue, s.received, i.PrimaryVendorId, i.standardPalletQuantity
from inventsum s WITH (INDEX(I_174CLOSEDITEMDIMIDX),NOLOCK),
SELECT k.itemid AS itemid,
(CASE WHEN ISNULL(bm.mmfitemid, '') != '' THEN bm.mmfitemid ELSE mm.mmfitemid END) AS mmfitemid,
(CASE WHEN ISNULL(bm.itembarcode, '') != '' THEN bm.itembarcode ELSE mm.itembarcode END) AS itembarcode,
e.name AS name, d.inventlocationid AS inventlocationid, d.inventbatchid AS inventbatchid,
LEFT(CONVERT(varchar, ib.proddate, 121), 10) AS proddate,
LEFT(CONVERT(varchar, ib.expdate, 121), 10) AS expdate,
d.wmslocationid AS wmslocationid, d.wmspalletid AS wmspalletid, p.pallettypeid AS pallettypeid,
xz.inputblockingcauseid AS inputblockingcauseid, xz.outputblockingcauseid AS outputblockingcauseid,
d.inventserialid AS inventserialid, d.inventownerid_via AS inventownerid_via,
d.inventlabelid_via AS inventlabelid_via, d.inventtaxstampid AS inventtaxstampid,
(CASE WHEN ISNULL(bm.CaseQTY, 0) != 0 THEN bm.CaseQTY ELSE mm.CaseQTY END) AS caseqty,
k.standardPalletQuantity AS palletqty,
(CASE WHEN ISNULL(bm.caseheight, 0) != 0 THEN bm.caseheight ELSE mm.caseheight END) AS caseheight,
(CASE WHEN ISNULL(bm.casewidth, 0) != 0 THEN bm.casewidth ELSE mm.casewidth END) AS casewidth,
(CASE WHEN ISNULL(bm.casedepth, 0) != 0 THEN bm.casedepth ELSE mm.casedepth END) AS casedepth,
(CASE WHEN ISNULL(bm.casebarcode, '') != '' THEN bm.casebarcode ELSE mm.casebarcode END) AS casebarcode,
(CASE WHEN ISNULL(bm.casebrutoweight, 0) != 0 THEN bm.casebrutoweight ELSE mm.casebrutoweight END) AS casebrutoweight,
(CASE WHEN ISNULL(bm.alcopct, 0) != 0 THEN bm.alcopct ELSE mm.alcopct END) AS alcopct,
(CASE WHEN ISNULL(bm.blockqty, 0) != 0 THEN bm.blockqty ELSE mm.blockqty END) AS blockqty,
(CASE WHEN ISNULL(bm.exciseproductregnum, '') != ''
THEN bm.exciseproductregnum
ELSE mm.exciseproductregnum
END) AS exciseproductregnum,
SUM(k.postedqty + k.received + k.registered) AS postedqty,
SUM(k.registered) AS registeredqty,
SUM(k.reservordered + k.reservphysical) AS reservedqty, SUM(k.picked) AS pickedqty,
SUM(k.postedqty - k.reservordered - k.reservphysical - k.picked + k.registered) AS freeqty,
SUM(k.ordered) AS ordered, SUM(k.postedvalue) AS postedvalue,
k.MMFItemProductGroupId AS mmfitemproductgroupid,
SUM(CASE WHEN bm.CaseQTY IS NULL
THEN (k.postedqty / mm.CaseQTY)
ELSE (k.postedqty / bm.CaseQTY)
END) AS laoseiskaste,
SUM(CASE WHEN bm.CaseQTY IS NULL
THEN ((k.postedqty - k.reservordered - k.reservphysical - k.picked + k.registered) / mm.CaseQTY)
ELSE ((k.postedqty - k.reservordered - k.reservphysical - k.picked + k.registered) / bm.CaseQTY)
END) AS vabakaste
FROM (SELECT s.itemid, i.product, i.ItemMiscRefId, i.MMFItemProductGroupId, s.INVENTDIMID,
s.postedqty, s.registered, s.reservordered, s.reservphysical, s.picked,
s.ordered, s.postedvalue, s.received, i.PrimaryVendorId, i.standardPalletQuantity
FROM inventsum s WITH (INDEX(I_174CLOSEDITEMDIMIDX), NOLOCK),
inventtable i WITH (INDEX([I_175ITEMIDX]), NOLOCK)
WHERE s.itemid = i.itemid
AND s.DATAAREAID = #Var1
AND i.DATAAREAID = #Var1
AND s.PARTITION = 5637144576
AND i.PARTITION = 5637144576
AND RIGHT(s.ITEMID, 2) = 'LA'
AND s.CLOSED = 0
AND (s.POSTEDQTY != 0
OR s.reservordered + s.reservphysical != 0
OR s.ordered != 0
)
) k
JOIN inventdim d WITH (INDEX(I_698DIMIDIDX), NOLOCK)
ON (k.INVENTDIMID = d.INVENTDIMID
AND d.DATAAREAID = #Var3
AND d.PARTITION = 5637144576)
LEFT OUTER JOIN EcoresProductTranslation e WITH (INDEX(I_6869PRODUCTLANGUAGEIDX))
ON (k.product = e.product
AND e.languageid = 'et'
AND e.PARTITION = 5637144576)
LEFT OUTER JOIN WMSPALLET p
ON (p.WMSPALLETID = d.WMSPALLETID
AND p.PARTITION = 5637144576
AND p.DATAAREAID = #Var4)
LEFT OUTER JOIN InventItemMisc mm WITH (INDEX(I_103616RecId))
ON (mm.RecId = k.ItemMiscRefId
AND mm.PARTITION = 5637144576)
LEFT OUTER JOIN InventBatch ib WITH (INDEX(I_752itemBatchIdx))
ON (ib.ItemId = k.ItemId
AND ib.InventBatchId = d.InventBatchId
AND ib.PARTITION = 5637144576
AND ib.DATAAREAID = #Var5)
LEFT OUTER JOIN InventItemMisc bm WITH (INDEX(I_103616RecId))
ON (bm.RecId = ib.ItemMiscRefId
AND bm.PARTITION = 5637144576)
JOIN WMSLOCATIOn xz WITH (INDEX(/*I672COORDINATEDIDX*/ I_672LOCATIONIDX))
ON (xz.inventlocationID = d.inventlocationID
AND xz.wmslocationid = d.wmslocationid
AND xz.partition = 5637144576
AND xz.dataareaid = 'EWH')
WHERE 1 = 1
GROUP BY k.itemid,
(CASE WHEN ISNULL(bm.mmfitemid, '') != '' THEN bm.mmfitemid ELSE mm.mmfitemid END),
(CASE WHEN ISNULL(bm.itembarcode, '') != '' THEN bm.itembarcode ELSE mm.itembarcode END),
e.name, d.inventlocationid, d.inventbatchid, LEFT(CONVERT(varchar, ib.proddate, 121), 10),
LEFT(CONVERT(varchar, ib.expdate, 121), 10), d.wmslocationid, d.wmspalletid,
p.pallettypeid, xz.inputblockingcauseid, xz.outputblockingcauseid, d.inventserialid,
d.inventownerid_via, d.inventlabelid_via, d.inventtaxstampid,
(CASE WHEN ISNULL(bm.CaseQTY, 0) != 0 THEN bm.CaseQTY ELSE mm.CaseQTY END),
k.standardPalletQuantity,
(CASE WHEN ISNULL(bm.caseheight, 0) != 0 THEN bm.caseheight ELSE mm.caseheight END),
(CASE WHEN ISNULL(bm.casewidth, 0) != 0 THEN bm.casewidth ELSE mm.casewidth END),
(CASE WHEN ISNULL(bm.casedepth, 0) != 0 THEN bm.casedepth ELSE mm.casedepth END),
(CASE WHEN ISNULL(bm.casebarcode, '') != '' THEN bm.casebarcode ELSE mm.casebarcode END),
(CASE WHEN ISNULL(bm.casebrutoweight, 0) != 0 THEN bm.casebrutoweight ELSE mm.casebrutoweight END),
(CASE WHEN ISNULL(bm.alcopct, 0) != 0 THEN bm.alcopct ELSE mm.alcopct END),
(CASE WHEN ISNULL(bm.blockqty, 0) != 0 THEN bm.blockqty ELSE mm.blockqty END),
(CASE WHEN ISNULL(bm.exciseproductregnum, '') != ''
THEN bm.exciseproductregnum
ELSE mm.exciseproductregnum
END),
k.MMFItemProductGroupId
ORDER BY k.itemid,
(CASE WHEN ISNULL(bm.mmfitemid, '') != '' THEN bm.mmfitemid ELSE mm.mmfitemid END),
(CASE WHEN ISNULL(bm.itembarcode, '') != '' THEN bm.itembarcode ELSE mm.itembarcode END),
e.name, d.inventlocationid, d.inventbatchid, LEFT(CONVERT(varchar, ib.proddate, 121), 10),
LEFT(CONVERT(varchar, ib.expdate, 121), 10), d.wmslocationid, d.wmspalletid,
p.pallettypeid, xz.inputblockingcauseid, xz.outputblockingcauseid,
d.inventserialid, d.inventownerid_via, d.inventlabelid_via, d.inventtaxstampid,
(CASE WHEN ISNULL(bm.CaseQTY, 0) != 0 THEN bm.CaseQTY ELSE mm.CaseQTY END),
k.standardPalletQuantity,
(CASE WHEN ISNULL(bm.caseheight, 0) != 0 THEN bm.caseheight ELSE mm.caseheight END),
(CASE WHEN ISNULL(bm.casewidth, 0) != 0 THEN bm.casewidth ELSE mm.casewidth END),
(CASE WHEN ISNULL(bm.casedepth, 0) != 0 THEN bm.casedepth ELSE mm.casedepth END),
(CASE WHEN ISNULL(bm.casebarcode, '') != '' THEN bm.casebarcode ELSE mm.casebarcode END),
(CASE WHEN ISNULL(bm.casebrutoweight, 0) != 0 THEN bm.casebrutoweight ELSE mm.casebrutoweight END),
(CASE WHEN ISNULL(bm.alcopct, 0) != 0 THEN bm.alcopct ELSE mm.alcopct END),
(CASE WHEN ISNULL(bm.blockqty, 0) != 0 THEN bm.blockqty ELSE mm.blockqty END),
(CASE WHEN ISNULL(bm.exciseproductregnum, '') != ''
THEN bm.exciseproductregnum
ELSE mm.exciseproductregnum
END),
k.MMFItemProductGroupId;
Error in SQL:Error in SQL:[Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Divide by zero error encountered.

In SSMS, hit Ctrl+F to open the Find & Replace dialogue box. Search the query for all instances of /. This will tell you everywhere that division is happening, plus some false positives.
In every single instance, the query is dividing by mm.CaseQTY or bm.CaseQTY. Those are the only two values, and the only two tables you have to worry about. One or the other of them is coming through as a zero.
We don't have access to your database, so we can't help you troubleshoot the data issue, but that's how I'd go about deciding where to start looking.

Related

The multi-part identifier could not be bound sql error

I have taken over the support of an Excel 2010 macro and need to change the sort order of a recordset.
The query below worked before I attempted to change the order by adding rl.list_order.
Now I'm getting the error "The multi-part identifier could not be bound" and have tried many alternatives and have researched on this site for a solution but haven't been able to solve this. Can someone please help.
SELECT ips_rc.project, lfbe.Category, ips_rc.roster_id, ips_rc.role_category, ips_rc.role_title AS Role, ips_rc.role_code, ips_rc.role_title + ' (' + ips_rc.role_code + ')' AS PS_Role, CASE WHEN ISNULL(lfbe.Pronto_Role_Code, '') = '' THEN 'TO_BE_MAPPED' ELSE ISNULL(lfbe.Pronto_Role_Code, '') END AS Pronto_Role_Code, CASE WHEN ISNULL(lfbe.Pronto_Role_Code_Description, '') = '' THEN ips_rc.role_title ELSE ISNULL(lfbe.Pronto_Role_Code_Description, '') END AS Pronto_Role_Code_Description, ISNULL(lfbe.Rate, 0) AS Rate, CASE WHEN ISNULL(lfbe.Pronto_Role_Code_Old, '') = '' THEN ips_rc.role_title ELSE lfbe.Pronto_Role_Code_Old END AS Pronto_Role_Code_Old, CASE WHEN ISNULL(lfbe.Pronto_Role_Code_Description_Old, '') = '' THEN 'TO_BE_MAPPED' ELSE lfbe.Pronto_Role_Code_Description_Old END AS Pronto_Role_Code_Description_Old, ips_rc.Shift, ips_rc.UOM, ips_rc.Date, ips_rc.DHours, ips_rc.NHours FROM (SELECT psrc.project, pr_jcm.customer, pr_jcm.subcode, psrc.roster_id, psrc.role_id, psrc.role_category, psrc.role_title,
psrc.role_code, CASE WHEN SUM(CASE WHEN psrc.Date BETWEEN psrc.start_date AND psrc.end_date THEN psrc.NWorkHours ELSE 0 END) OVER (PARTITION BY psrc.project, psrc.roster_id) >= SUM(CASE WHEN psrc.Date BETWEEN psrc.start_date AND psrc.end_date THEN psrc.DWorkHours ELSE 0 END) OVER (PARTITION BY psrc.project, psrc.roster_id) THEN 'Night Shifts' ELSE 'Day Shifts' END AS Shift, 'HOURS' AS UOM, psrc.Date, psrc.DHours, psrc.NHours FROM (SELECT rcd.project, rcd.start_date, rcd.end_date, rcd.roster_id, rcd.role1_id AS role_id, CASE WHEN rb_test1.role1_id IS NOT NULL THEN rb_test1.category WHEN rb_test2.role1_id IS NOT NULL THEN rb_test2.category WHEN rb_test3.role1_id IS NOT NULL THEN rb_test3.category ELSE rcd.role_category END AS role_category, CASE WHEN rb_test1.role1_id IS NOT NULL THEN rb_test1.title WHEN rb_test2.role1_id IS NOT NULL THEN rb_test2.title WHEN rb_test3.role1_id IS NOT NULL THEN rb_test3.title ELSE rcd.role_title END AS role_title, CASE WHEN rb_test1.role1_id IS NOT NULL THEN CAST(rb_test1.band_r
ole_id AS VARCHAR) WHEN rb_test2.role1_id IS NOT NULL THEN CAST(rb_test2.band_role_id AS VARCHAR) WHEN rb_test3.role1_id IS NOT NULL THEN CAST(rb_test3.band_role_id AS VARCHAR) ELSE rcd.role_code END AS role_code, rcd.shift_date AS Date, SUM(CASE WHEN rcd.shift_ampm = 'day' THEN rcd.shift_time ELSE 0 END) AS DHours, SUM(CASE WHEN rcd.shift_ampm = 'day' AND rcd.shift_type = 'work' THEN rcd.shift_time ELSE 0 END) AS DWorkHours, SUM(CASE WHEN rcd.shift_ampm = 'day' AND rcd.shift_type = 'eqmob' THEN rcd.shift_time ELSE 0 END) AS DEqmobHours, SUM(CASE WHEN rcd.shift_ampm = 'day' AND rcd.shift_type = 'eqdemob' THEN rcd.shift_time ELSE 0 END) AS DEqdemobHours, SUM(CASE WHEN rcd.shift_ampm = 'night' THEN rcd.shift_time ELSE 0 END) AS NHours, SUM(CASE WHEN rcd.shift_ampm = 'night' AND rcd.shift_type = 'work' THEN rcd.shift_time ELSE 0 END) AS NWorkHours, SUM(CASE WHEN rcd.shift_ampm = 'night' AND rcd.shift_type = 'eqmob' THEN rcd.shift_time ELSE 0 END) AS NEqmobHours, SUM(CASE WHEN rcd.shift_ampm = 'night' AND rcd.sh
ift_type = 'eqdemob' THEN rcd.shift_time ELSE 0 END) AS NEqdemobHours FROM OPENQUERY([LFMANAGE], 'SELECT p.job_no AS project, p.start_date, p.end_date, rs.roster_id, IFNULL(rs.role_id, 0) AS role1_id, IFNULL(r.role2_id, 0) AS role2_id, IFNULL(r.role3_id, 0) AS role3_id, rl.category AS role_category, rl.title AS role_title, rl.role_code AS role_code, rs.shift_date, rs.shift_ampm, rs.shift_time, rs.shift_type, s.client_id FROM lfmanage.t_roster_shift rs JOIN lfmanage.t_project AS p ON p.project_id = rs.project_id LEFT JOIN lfmanage.t_site AS s ON s.site_id = p.site_id JOIN lfmanage.t_roster AS r ON r.roster_id = rs.roster_id JOIN lfmanage.t_role AS rl ON rl.role_id = rs.role_id WHERE p.job_no = ''700704'' AND CASE WHEN ISNULL(rs.deleted) THEN 0 ELSE rs.deleted END = 0') AS rcd LEFT OUTER JOIN (SELECT client_id, band_role_id, title, CASE WHEN CHARINDEX(UPPER(title),'SUPER') > 0 THEN 'super' ELSE 'trade' END AS category, role1_id, role2_id, role3_id FROM OPENQUERY([LFMANAGE], 'SELECT br.client_id, MIN(brs.band_r
ole_id) AS band_role_id, br.title, brs.role1_id, brs.role2_id, brs.role3_id FROM t_band_role_set AS brs INNER JOIN t_band_role AS br ON br.band_role_id = brs.band_role_id WHERE IFNULL(brs.role1_id, 0) <> 0 AND IFNULL(brs.role2_id, 0) <> 0 AND IFNULL(brs.role3_id, 0) <> 0 GROUP BY br.client_id, br.title, brs.role1_id, brs.role2_id, brs.role3_id')) AS rb_test1 ON rb_test1.client_id = rcd.client_id AND rb_test1.role1_id = rcd.role1_id AND rb_test1.role2_id = rcd.role2_id AND rb_test1.role3_id = rcd.role3_id LEFT OUTER JOIN (SELECT client_id, band_role_id, title, CASE WHEN CHARINDEX(UPPER(title),'SUPER') > 0 THEN 'super' ELSE 'trade' END AS category, role1_id, role2_id FROM OPENQUERY([LFMANAGE], 'SELECT br.client_id, MIN(brs.band_role_id) AS band_role_id, br.title, brs.role1_id, brs.role2_id FROM t_band_role_set AS brs INNER JOIN t_band_role AS br ON br.band_role_id = brs.band_role_id WHERE IFNULL(brs.role1_id, 0) <> 0 AND IFNULL(brs.role2_id, 0) <> 0 GROUP BY br.client_id, br.title, brs.role1_id, brs.role2_id '
)) AS rb_test2 ON rb_test2.client_id = rcd.client_id AND rb_test2.role1_id = rcd.role1_id AND rb_test2.role2_id = rcd.role2_id LEFT OUTER JOIN (SELECT client_id, band_role_id, title, CASE WHEN CHARINDEX(UPPER(title),'SUPER') > 0 THEN 'super' ELSE 'trade' END AS category, role1_id, role3_id FROM OPENQUERY([LFMANAGE], 'SELECT br.client_id, MIN(brs.band_role_id) AS band_role_id, br.title, brs.role1_id, brs.role3_id FROM t_band_role_set AS brs INNER JOIN t_band_role AS br ON br.band_role_id = brs.band_role_id WHERE IFNULL(brs.role1_id, 0) <> 0 AND IFNULL(brs.role3_id, 0) <> 0 GROUP BY br.client_id, br.title, brs.role1_id, brs.role3_id ')) AS rb_test3 ON rb_test3.client_id = rcd.client_id AND rb_test3.role1_id = rcd.role1_id AND rb_test3.role3_id = rcd.role3_id WHERE rcd.shift_date > '2017-01-01' GROUP BY rcd.project, rcd.start_date, rcd.end_date, rcd.roster_id, rcd.role1_id, CASE WHEN rb_test1.role1_id IS NOT NULL THEN rb_test1.category WHEN rb_test2.role1_id IS NOT NULL THEN rb_test2.category WHEN rb_test3.role
1_id IS NOT NULL THEN rb_test3.category ELSE rcd.role_category END, CASE WHEN rb_test1.role1_id IS NOT NULL THEN rb_test1.title WHEN rb_test2.role1_id IS NOT NULL THEN rb_test2.title WHEN rb_test3.role1_id IS NOT NULL THEN rb_test3.title ELSE rcd.role_title END, CASE WHEN rb_test1.role1_id IS NOT NULL THEN CAST(rb_test1.band_role_id AS VARCHAR) WHEN rb_test2.role1_id IS NOT NULL THEN CAST(rb_test2.band_role_id AS VARCHAR) WHEN rb_test3.role1_id IS NOT NULL THEN CAST(rb_test3.band_role_id AS VARCHAR) ELSE rcd.role_code END, rcd.shift_date) AS psrc INNER JOIN (SELECT job_no AS project, Client AS customer, '3700002213' AS subcode FROM [dbo].[vw_PlanningSystem_Projects] WHERE job_no = '700704') AS pr_jcm ON pr_jcm.project = psrc.project) AS ips_rc LEFT OUTER JOIN (SELECT rates.Client, rates.SubCode, mapping.Category, mapping.Shift, mapping.IPS_Role_Code, rates.Pronto_Role_Code, rates.Pronto_Role_Code_Description, rates.Rate, rates.Pronto_Role_Code_Old, rates.Pronto_Role_Code_Description_Old FROM (SELECT UPPER(Ca
tegory) AS Category, 'Day Shifts' AS Shift, IPS_Role_Code, Day_Cost_Code As Pronto_Role_Code FROM [LFBudgetEstimate].[dbo].[LFBE_RoleCode_MasterMapping] UNION ALL SELECT UPPER(Category) AS Category, 'Night Shifts' AS Shift, IPS_Role_Code, Night_Cost_Code As Pronto_Role_Code FROM [LFBudgetEstimate].[dbo].[LFBE_RoleCode_MasterMapping]) AS mapping INNER JOIN (SELECT Client, SubCode, CASE WHEN Shift = 'Day Shift' THEN 'Day Shifts' WHEN Shift = 'Night Shift' THEN 'Night Shifts' Else '' END AS Shift, Pronto_Role_Code, Pronto_Role_Code_Description, Rate, Pronto_Role_Code_Old, Pronto_Role_Code_Description_Old FROM [LFBudgetEstimate].[dbo].[LFBE_SubCodes_Rates]) AS rates ON rates.Shift = mapping.Shift AND rates.Pronto_Role_Code = mapping.Pronto_Role_Code) AS lfbe ON lfbe.Client = ips_rc.customer AND lfbe.SubCode = ips_rc.subCode AND lfbe.Shift = ips_rc.Shift AND lfbe.IPS_Role_Code = ips_rc.role_code ORDER BY ips_rc.project ASC, ips_rc.role_title ASC, rl.list_order
Thanks for your help
Even with the formatting, you've got a lot going on here... Stack Overflow veterans, I'm just starting to dip my toes in here, so if this isn't correct, give me some grace.
In your first OPENQUERY statement, I don't see rl.list_order as a field being returned. If that's a column you're trying to ORDER BY, I think you should be able to add rl.list_order to your SELECT list within that statement which you alias as rcd.
Since that's within a nested sub-query, you'll want to elevate it to each of the calling queries. I think it's something like this... Try it out and post back with any errors.
SELECT ips_rc.ListOrder
, ips_rc.project
, lfbe.Category
, ips_rc.roster_id
, ips_rc.role_category
, ips_rc.role_title AS [ROLE]
, ips_rc.role_code
, ips_rc.role_title + ' (' + ips_rc.role_code + ')' AS PS_Role
, CASE
WHEN ISNULL(lfbe.Pronto_Role_Code, '') = ''
THEN 'TO_BE_MAPPED'
ELSE ISNULL(lfbe.Pronto_Role_Code, '')
END AS Pronto_Role_Code
, CASE
WHEN ISNULL(lfbe.Pronto_Role_Code_Description, '') = ''
THEN ips_rc.role_title
ELSE ISNULL(lfbe.Pronto_Role_Code_Description, '')
END AS Pronto_Role_Code_Description
, ISNULL(lfbe.Rate, 0) AS Rate
, CASE
WHEN ISNULL(lfbe.Pronto_Role_Code_Old, '') = ''
THEN ips_rc.role_title
ELSE lfbe.Pronto_Role_Code_Old
END AS Pronto_Role_Code_Old
, CASE
WHEN ISNULL(lfbe.Pronto_Role_Code_Description_Old, '') = ''
THEN 'TO_BE_MAPPED'
ELSE lfbe.Pronto_Role_Code_Description_Old
END AS Pronto_Role_Code_Description_Old
, ips_rc.Shift
, ips_rc.UOM
, ips_rc.DATE
, ips_rc.DHours
, ips_rc.NHours
FROM (
SELECT psrc.ListOrder -- Added
, psrc.project
, pr_jcm.customer
, pr_jcm.subcode
, psrc.roster_id
, psrc.role_id
, psrc.role_category
, psrc.role_title
, psrc.role_code
, CASE
WHEN SUM(CASE
WHEN psrc.DATE BETWEEN psrc.start_date
AND psrc.end_date
THEN psrc.NWorkHours
ELSE 0
END) OVER (PARTITION BY psrc.project, psrc.roster_id) >= SUM(CASE
WHEN psrc.DATE BETWEEN psrc.start_date
AND psrc.end_date
THEN psrc.DWorkHours
ELSE 0
END) OVER (PARTITION BY psrc.project, psrc.roster_id)
THEN 'Night Shifts'
ELSE 'Day Shifts'
END AS Shift, 'HOURS' AS UOM, psrc.DATE, psrc.DHours, psrc.NHours
FROM (
SELECT rcd.list_order --Added
, rcd.project
, rcd.start_date
, rcd.end_date
, rcd.roster_id
, rcd.role1_id AS role_id
, CASE
WHEN rb_test1.role1_id IS NOT NULL
THEN rb_test1.category
WHEN rb_test2.role1_id IS NOT NULL
THEN rb_test2.category
WHEN rb_test3.role1_id IS NOT NULL
THEN rb_test3.category
ELSE rcd.role_category
END AS role_category
, CASE
WHEN rb_test1.role1_id IS NOT NULL
THEN rb_test1.title
WHEN rb_test2.role1_id IS NOT NULL
THEN rb_test2.title
WHEN rb_test3.role1_id IS NOT NULL
THEN rb_test3.title
ELSE rcd.role_title
END AS role_title
, CASE
WHEN rb_test1.role1_id IS NOT NULL
THEN CAST(rb_test1.band_role_id AS VARCHAR)
WHEN rb_test2.role1_id IS NOT NULL
THEN CAST(rb_test2.band_role_id AS VARCHAR)
WHEN rb_test3.role1_id IS NOT NULL
THEN CAST(rb_test3.band_role_id AS VARCHAR)
ELSE rcd.role_code
END AS role_code, rcd.shift_date AS DATE
, SUM(CASE
WHEN rcd.shift_ampm = 'day'
THEN rcd.shift_time
ELSE 0
END) AS DHours
, SUM(CASE
WHEN rcd.shift_ampm = 'day'
AND rcd.shift_type = 'work'
THEN rcd.shift_time
ELSE 0
END) AS DWorkHours
, SUM(CASE
WHEN rcd.shift_ampm = 'day'
AND rcd.shift_type = 'eqmob'
THEN rcd.shift_time
ELSE 0
END) AS DEqmobHours
, SUM(CASE
WHEN rcd.shift_ampm = 'day'
AND rcd.shift_type = 'eqdemob'
THEN rcd.shift_time
ELSE 0
END) AS DEqdemobHours
, SUM(CASE
WHEN rcd.shift_ampm = 'night'
THEN rcd.shift_time
ELSE 0
END) AS NHours
, SUM(CASE
WHEN rcd.shift_ampm = 'night'
AND rcd.shift_type = 'work'
THEN rcd.shift_time
ELSE 0
END) AS NWorkHours
, SUM(CASE
WHEN rcd.shift_ampm = 'night'
AND rcd.shift_type = 'eqmob'
THEN rcd.shift_time
ELSE 0
END) AS NEqmobHours
, SUM(CASE
WHEN rcd.shift_ampm = 'night'
AND rcd.shift_type = 'eqdemob'
THEN rcd.shift_time
ELSE 0
END) AS NEqdemobHours
FROM OPENQUERY([LFMANAGE], 'SELECT p.job_no AS project, p.start_date, p.end_date, rs.roster_id, IFNULL(rs.role_id, 0) AS role1_id, IFNULL(r.role2_id, 0) AS role2_id, IFNULL(r.role3_id, 0) AS role3_id, rl,ListOrder, rl.category AS role_category, rl.title AS role_title, rl.role_code AS role_code, rs.shift_date, rs.shift_ampm, rs.shift_time, rs.shift_type, s.client_id FROM lfmanage.t_roster_shift rs JOIN lfmanage.t_project AS p ON p.project_id = rs.project_id LEFT JOIN lfmanage.t_site AS s ON s.site_id = p.site_id JOIN lfmanage.t_roster AS r ON r.roster_id = rs.roster_id JOIN lfmanage.t_role AS rl ON rl.role_id = rs.role_id WHERE p.job_no = ''700704'' AND CASE WHEN ISNULL(rs.deleted) THEN 0 ELSE rs.deleted END = 0') AS rcd --Added
LEFT JOIN (
SELECT client_id
, band_role_id
, title
, CASE
WHEN CHARINDEX(UPPER(title), 'SUPER') > 0
THEN 'super'
ELSE 'trade'
END AS category
, role1_id
, role2_id
, role3_id
FROM OPENQUERY([LFMANAGE], 'SELECT br.client_id, MIN(brs.band_role_id) AS band_role_id, br.title, brs.role1_id, brs.role2_id, brs.role3_id FROM t_band_role_set AS brs INNER JOIN t_band_role AS br ON br.band_role_id = brs.band_role_id WHERE IFNULL(brs.role1_id, 0) <> 0 AND IFNULL(brs.role2_id, 0) <> 0 AND IFNULL(brs.role3_id, 0) <> 0 GROUP BY br.client_id, br.title, brs.role1_id, brs.role2_id, brs.role3_id')
) AS rb_test1
ON rb_test1.client_id = rcd.client_id
AND rb_test1.role1_id = rcd.role1_id
AND rb_test1.role2_id = rcd.role2_id
AND rb_test1.role3_id = rcd.role3_id
LEFT JOIN (
SELECT client_id, band_role_id, title, CASE
WHEN CHARINDEX(UPPER(title), 'SUPER') > 0
THEN 'super'
ELSE 'trade'
END AS category, role1_id, role2_id
FROM OPENQUERY([LFMANAGE], 'SELECT br.client_id, MIN(brs.band_role_id) AS band_role_id, br.title, brs.role1_id, brs.role2_id FROM t_band_role_set AS brs INNER JOIN t_band_role AS br ON br.band_role_id = brs.band_role_id WHERE IFNULL(brs.role1_id, 0) <> 0 AND IFNULL(brs.role2_id, 0) <> 0 GROUP BY br.client_id, br.title, brs.role1_id, brs.role2_id ')
) AS rb_test2
ON rb_test2.client_id = rcd.client_id
AND rb_test2.role1_id = rcd.role1_id
AND rb_test2.role2_id = rcd.role2_id
LEFT JOIN (
SELECT client_id, band_role_id, title, CASE
WHEN CHARINDEX(UPPER(title), 'SUPER') > 0
THEN 'super'
ELSE 'trade'
END AS category, role1_id, role3_id
FROM OPENQUERY([LFMANAGE], 'SELECT br.client_id, MIN(brs.band_role_id) AS band_role_id, br.title, brs.role1_id, brs.role3_id FROM t_band_role_set AS brs INNER JOIN t_band_role AS br ON br.band_role_id = brs.band_role_id WHERE IFNULL(brs.role1_id, 0) <> 0 AND IFNULL(brs.role3_id, 0) <> 0 GROUP BY br.client_id, br.title, brs.role1_id, brs.role3_id ')
) AS rb_test3
ON rb_test3.client_id = rcd.client_id
AND rb_test3.role1_id = rcd.role1_id
AND rb_test3.role3_id = rcd.role3_id
WHERE rcd.shift_date > '2017-01-01'
GROUP BY rcd.list_order --Added
, rcd.project
, rcd.start_date
, rcd.end_date
, rcd.roster_id
, rcd.role1_id
, CASE
WHEN rb_test1.role1_id IS NOT NULL
THEN rb_test1.category
WHEN rb_test2.role1_id IS NOT NULL
THEN rb_test2.category
WHEN rb_test3.ROLE1_id IS NOT NULL
THEN rb_test3.category
ELSE rcd.role_category
END
, CASE
WHEN rb_test1.role1_id IS NOT NULL
THEN rb_test1.title
WHEN rb_test2.role1_id IS NOT NULL
THEN rb_test2.title
WHEN rb_test3.role1_id IS NOT NULL
THEN rb_test3.title
ELSE rcd.role_title
END
, CASE
WHEN rb_test1.role1_id IS NOT NULL
THEN CAST(rb_test1.band_role_id AS VARCHAR)
WHEN rb_test2.role1_id IS NOT NULL
THEN CAST(rb_test2.band_role_id AS VARCHAR)
WHEN rb_test3.role1_id IS NOT NULL
THEN CAST(rb_test3.band_role_id AS VARCHAR)
ELSE rcd.role_code
END
, rcd.shift_date
) AS psrc
INNER JOIN (
SELECT job_no AS project
, Client AS customer
, '3700002213' AS subcode
FROM [dbo].[vw_PlanningSystem_Projects]
WHERE job_no = '700704'
) AS pr_jcm
ON pr_jcm.project = psrc.project
) AS ips_rc
LEFT JOIN (
SELECT rates.Client
, rates.SubCode
, mapping.Category
, mapping.Shift
, mapping.IPS_Role_Code
, rates.Pronto_Role_Code
, rates.Pronto_Role_Code_Description
, rates.Rate
, rates.Pronto_Role_Code_Old
, rates.Pronto_Role_Code_Description_Old
FROM (
SELECT UPPER(Category) AS Category
, 'Day Shifts' AS Shift
, IPS_Role_Code
, Day_Cost_Code AS Pronto_Role_Code
FROM [LFBudgetEstimate].[dbo].[LFBE_RoleCode_MasterMapping]
UNION ALL
SELECT UPPER(Category) AS Category
, 'Night Shifts' AS Shift
, IPS_Role_Code
, Night_Cost_Code AS Pronto_Role_Code
FROM [LFBudgetEstimate].[dbo].[LFBE_RoleCode_MasterMapping]
) AS mapping
INNER JOIN (
SELECT Client
, SubCode
, CASE
WHEN Shift = 'Day Shift'
THEN 'Day Shifts'
WHEN Shift = 'Night Shift'
THEN 'Night Shifts'
ELSE ''
END AS Shift
, Pronto_Role_Code
, Pronto_Role_Code_Description
, Rate
, Pronto_Role_Code_Old
, Pronto_Role_Code_Description_Old
FROM [LFBudgetEstimate].[dbo].[LFBE_SubCodes_Rates]
) AS rates
ON rates.Shift = mapping.Shift
AND rates.Pronto_Role_Code = mapping.Pronto_Role_Code
) AS lfbe
ON lfbe.Client = ips_rc.customer
AND lfbe.SubCode = ips_rc.subCode
AND lfbe.Shift = ips_rc.Shift
AND lfbe.IPS_Role_Code = ips_rc.role_code
ORDER BY ips_rc.project ASC, ips_rc.role_title ASC, ips_rc.list_order ASC
You're right CSharp821 there's an awful lot going on there. I made the changes you suggested and it now works!
You are trying to access alias rl, however the rl alias is only visible within the OPENQUERY which has an alias of rcd. Try order by rcd.list_order instead of rl.list_order

How do I escape <> for this SQL in a XML file

I am trying to store the following sql in a bean within an XML file. I am trying to escape the greater than and less than signs, however I seem to still be getting an error in Eclipse. I must not understand how to properly escape these signs. I count six less than and greater than signs, which I have attempted to escape.
Here's my attempt:
<property name="SQL" value="<><><><><><>"
"SELECT TO_CHAR(SYSDATE,'YYYY-MM-DD') SQL_RUN_DT
,'STG_DISB_HOLD_TH' SRC_TBL
,A1.DISB_DT
,A1.CPC
,A1.AWARD_YR
,COUNT(1) ROW_CNT
,SUM(A1.APPL_NBR) APPL_NBR_SUM
,SUM(A1.TSYS_SCHL_ID) TSYS_SCHL_ID_SUM
,SUM(TO_NUMBER(A1.DISB_NBR)) DISB_NBR_SUM
,SUM(A1.DISB_SEQ_NBR) DISB_SEQ_NBR_SUM
,SUM(CASE WHEN A1.DISB_STAT_CD = 'R' AND A1.DISB_SEQ_NBR = 1 THEN 1
ELSE A1.INTNL_APPL_SEQ_NBR + 1
END) INTERNAL_DISB_SEQ_SUM
,MIN(A1.DISB_RCVD_DT) DISB_RCVD_DT_MIN
,MAX(A1.DISB_RCVD_DT) DISB_RCVD_DT_MAX
,SUM(CASE WHEN A1.DISB_STAT_CD = 'P' THEN 1 ELSE 0 END) DISB_STAT_CD_P
,SUM(CASE WHEN A1.DISB_STAT_CD = 'R' THEN 1 ELSE 0 END) DISB_STAT_CD_R
,MIN(A1.PYMT_START_DT) PYMT_START_DT_MIN
,MAX(A1.PYMT_START_DT) PYMT_START_DT_MAX
,COUNT(DISTINCT A1.SCHL_ENROLL_CD) SCHL_ENROLL_CD_CNT
,SUM(TO_NUMBER(A1.NET_TRANS_CD)) NET_TRANS_CD_SUM
,SUM(A1.NET_TRANS_AMT) NET_TRANS_AMT_SUM
,SUM(CASE WHEN A1.DISB_STAT_CD = 'R' AND A1.DISB_SEQ_NBR = 1 AND A1.NET_C_OR_D_IND = 'D' THEN A1.NET_TRANS_AMT + A1.NET_TRANS_AMT
WHEN A1.DISB_STAT_CD = 'R' AND A1.DISB_SEQ_NBR = 1 AND A1.NET_C_OR_D_IND <> 'D' THEN A1.NET_TRANS_AMT - A1.NET_TRANS_AMT
WHEN (A1.DISB_STAT_CD <> 'R' OR A1.DISB_SEQ_NBR <> 1) AND A1.NET_C_OR_D_IND = 'D' THEN A1.SUM_NET_AMT + A1.NET_TRANS_AMT
WHEN (A1.DISB_STAT_CD <> 'R' OR A1.DISB_SEQ_NBR <> 1) AND A1.NET_C_OR_D_IND <> 'D' THEN A1.SUM_NET_AMT - A1.NET_TRANS_AMT
ELSE 0
END) SUM_NET_AMT_SUM
,SUM(CASE WHEN A1.ENRL_STATUS_CD = 'F' THEN 1 ELSE 0 END) ENRL_STATUS_CD_F
,SUM(CASE WHEN A1.ENRL_STATUS_CD = 'Q' THEN 1 ELSE 0 END) ENRL_STATUS_CD_Q
,SUM(CASE WHEN A1.ENRL_STATUS_CD = 'H' THEN 1 ELSE 0 END) ENRL_STATUS_CD_H
,SUM(CASE WHEN A1.ENRL_STATUS_CD = 'L' THEN 1 ELSE 0 END) ENRL_STATUS_CD_L
,SUM(CASE WHEN A1.ENRL_STATUS_CD IS NULL THEN 1 ELSE 0 END) ENRL_STATUS_CD_NULL
,COUNT(DISTINCT A1.PGM_CIP_CD) PGM_CIP_CD_CNT
,COUNT(DISTINCT A1.LEGACY_USER_ID) LEGACY_USER_ID_CNT
,COUNT(DISTINCT A1.MAINT_APP) MAINT_APP_CNT
,MIN(A1.MAINT_DTM) MAINT_DTM_MIN
,MAX(A1.MAINT_DTM) MAINT_DTM_MAX
,COUNT(DISTINCT A1.MAINT_USERID) MAINT_USERID_CNT
FROM
(
SELECT LM.TEACH_MASTER_ID
,SAM.APPL_NBR
,TO_NUMBER(SAM.AWARD_YR) AWARD_YR
,SAM.TSYS_SCHL_ID
,SAM.AWARD_NBR
,SAM.DISB_NBR
,SAM.DISB_SEQ_NBR
,SAM.CPC
,SAM.DISB_DT
,SAM.DISB_RCVD_DT
,SAM.DISB_STAT_CD
,SAM.PYMT_START_DT
,SAM.SCHL_ENROLL_CD
,SAM.NET_TRANS_CD
,CASE WHEN SAM.NET_C_OR_D_IND = 'C' THEN SAM.NET_TRANS_AMT * -1
WHEN SAM.NET_C_OR_D_IND IS NULL THEN 0
ELSE SAM.NET_TRANS_AMT
END NET_TRANS_AMT
,CASE WHEN SAM.NET_C_OR_D_IND = 'C' THEN SAM.GROSS_TRANS_AMT * -1
WHEN SAM.NET_C_OR_D_IND IS NULL THEN 0
ELSE SAM.GROSS_TRANS_AMT
END GROSS_TRANS_AMT
,CASE WHEN SAM.NET_C_OR_D_IND = 'C' THEN SAM.FEE_TRANS_AMT * -1
WHEN SAM.NET_C_OR_D_IND IS NULL THEN 0
ELSE SAM.FEE_TRANS_AMT
END FEE_TRANS_AMT
,CASE WHEN SAM.NET_C_OR_D_IND = 'C' THEN SAM.REBATE_TRANS_AMT * -1
WHEN SAM.NET_C_OR_D_IND IS NULL THEN 0
ELSE SAM.REBATE_TRANS_AMT
END REBATE_TRANS_AMT
,SAM.MAINT_DTM
,SAM.MAINT_USERID
,SAM.ENRL_STATUS_CD
,SAM.PGM_CIP_CD
,'BATCH' AS LEGACY_USER_ID
,'BATCH' AS MAINT_APP
,SAM.NET_C_OR_D_IND
,ROW_NUMBER() OVER (PARTITION BY SAM.APPL_NBR, SAM.AWARD_YR, SAM.TSYS_SCHL_ID, SAM.AWARD_NBR, SAM.DISB_NBR
ORDER BY DTSEQ.INTNL_APPL_SEQ_NBR DESC) ROW_NUM_PART
,COALESCE(DTSEQ.INTNL_APPL_SEQ_NBR,0) INTNL_APPL_SEQ_NBR
,DTSEQ.CHG_GROSS_TRANS_AMT DT_CHG_GROSS_TRANS_AMT
,DTSEQ.CHG_NET_TRANS_AMT DT_CHG_NET_TRANS_AMT
,DTSEQ.CHG_FEE_TRANS_AMT DT_CHG_FEE_TRANS_AMT
,DTSEQ.CHG_REBATE_TRANS_AMT DT_CHG_REBATE_TRANS_AMT
,COALESCE(DTSEQ.SUM_GROSS_AMT,0) SUM_GROSS_AMT
,COALESCE(DTSEQ.SUM_NET_AMT,0) SUM_NET_AMT
,COALESCE(DTSEQ.SUM_FEE_AMT,0) SUM_FEE_AMT
,COALESCE(DTSEQ.SUM_REBATE_AMT,0) SUM_REBATE_AMT
FROM MYSCHEMA.TEACH_MASTER LM
JOIN MYSCHEMA.STG_DISB_HOLD SAM
ON LM.APP_NUM_LEGACY = SAM.APPL_NBR
AND LM.ATTEND_SCHL_MASTER_ID = SAM.TSYS_SCHL_ID
AND LM.AWARD_YR = TO_NUMBER(SAM.AWARD_YR)
LEFT JOIN MYSCHEMA.STG_DISB_TRANS DTSEQ
ON SAM.APPL_NBR = DTSEQ.APPL_NBR
AND SAM.AWARD_YR = DTSEQ.AWARD_YR
AND SAM.TSYS_SCHL_ID = DTSEQ.TSYS_SCHL_ID
AND SAM.AWARD_NBR = DTSEQ.AWARD_NBR
AND SAM.DISB_NBR = DTSEQ.DISB_NBR
WHERE SAM.DISB_STAT_CD IN ('R','P')
AND SAM.NET_TRANS_CD IN ('0102','0131','0161','0189','0200')
) A1
WHERE A1.ROW_NUM_PART = 1
GROUP BY TO_CHAR(SYSDATE,'YYYY-MM-DD')
,'STG_DISB_HOLD_TH'
,A1.DISB_DT
,A1.CPC
,A1.AWARD_YR
;"/>
You have to escape them ALL:
WHEN A1.DISB_STAT_CD [..snip..] A1.NET_C_OR_D_IND <> 'D' THEN A1.NET_TRANS_AMT - A1.NET_TRANS_AMT
^^--missed a bunch of these
Plus, this next bit makes no sense:
<property name="SQL" value="<><><><><><>"
^---start attribute end attribute --^
"SELECT TO_CHAR(SYSDATE,'YYYY-MM-DD') SQL_RUN_DT
^---attribute value with no name for it

A subquery in a select causes my results to not return

Hello I have an issue with a very convoluted query, I did not write the query but I have to maintain it.
I have the below super long query which was working fine for a while(slow but fine) but some time in the last month it stopped working. we don't get an error it just times out returning results.
Now, if I run this fun query below with the first sub query within the selection criteria removed the results return the top 50 in 136 seconds.
If I leave it in it just times out after a few hours. Also to note if I take the sub query in the select statement and run it on it's own hard coding any values passed in to it returns the result in 0.004 seconds.
If I leave it all in but go to the very core query in this long query and put a restriction on the SDDOCO so it will return a single result I get the result in 94 seconds and it doesn't matter if I have the sub query in the select or not.
I think that one of the results is causing issues and bogging down the query but I can't think of a good way to figure out which item would cause this.. my result set when it returns is 47k records.
Any suggestions on where I can look or how I can investigate this further would be greatly appreciated.
SELECT
SUM((GL.GLAA/100) * (CAST(COALESCE((Select CXCRR from PRODDTA.F0015 F2 WHERE CXEFT = (SELECT MAX(CXEFT) FROM PRODDTA.F0015 F3 WHERE F3.CXEFT <= GL.GLDGJ) and CXCRCD = GL.GLCRCD AND CXCRDC ='USD'), 1) AS NUMERIC(15,4)))) TEST1,
SUM((GL.GLAA/100)) test2
FROM (SELECT MAX(SDAN8) SDAN8, MAX(SDMCU) SDMCU, MAX(SDDOCO) SDDOCO, MAX(SDDOC) SDDOC, MAX(SDSHAN) SDSHAN, CASE WHEN NVL(TRIM(TMURRF),' ') = ' ' then SDURRF ELSE TMURRF END SDURRF, MAX(SDDCTO) SDDCTO, MAX(SDDGL) SDDGL, MAX(SDASN) SDASN
, SUM(CASE WHEN IMGLPT like 'FG%' THEN (CASE WHEN NOT (UMCONV IS NULL) THEN SDSOQS/100 * UMCONV/10000000 else SDSOQS/100 END) ELSE 0 END) AS SDSOQS
, SUM(CASE WHEN IMGLPT = 'FG04' THEN (CASE WHEN NOT (UMCONV IS NULL) THEN SDSOQS/100 * UMCONV/10000000 ELSE SDSOQS/100 END) ELSE 0 END) AS AER_SDSOQS
, SUM(CASE WHEN IMGLPT like 'FG%' THEN (CASE WHEN SDSRP5 = '527' THEN (CASE WHEN NOT (UMCONV IS NULL) THEN SDSOQS/100 * UMCONV/10000000 ELSE SDSOQS/100 END) ELSE 0 END) ELSe 0 END) AS MDJ_SDSOQS
, MAX(SDIVD) SDIVD, MAX(SDADDJ) SDADDJ
, SUM(CASE WHEN SDWTUM = 'LB' THEN SDITWT WHEN UCCONV is not null then SDITWT*(UCCONV/10000000) WHEN CONV is not null THEN SDSOQS*CONV*10 ELSE 0 END)/10000 AS WEIGHT
,SUM(CASE WHEN IMGLPT like 'FG%' THEN
CASE
WHEN SDWTUM = 'LB' THEN SDITWT
WHEN UCCONV IS NOT NULL THEN SDITWT*(UCCONV/10000000)
WHEN CONV is not null THEN SDSOQS*CONV*10
ELSE 0 END
ELSE 0
end)/10000 as FG_WEIGHT,
SUM(CASE WHEN IMGLPT = 'FG04' THEN
CASE
WHEN SDWTUM = 'LB' THEN SDITWT
WHEN UCCONV IS NOT NULL THEN SDITWT*(UCCONV/10000000)
WHEN CONV is not null THEN SDSOQS*CONV*10
ELSE 0 END
ELSE 0
end)/10000 as AER_WEIGHT,
SUM(CASE WHEN SDSRP5 = '527' THEN
CASE
WHEN SDWTUM = 'LB' THEN SDITWT
WHEN UCCONV IS NOT NULL THEN SDITWT*(UCCONV/10000000)
WHEN CONV is not null THEN SDSOQS*CONV*10
ELSE 0 END
ELSE 0
end)/10000 as MDJ_WEIGHT,
SUM(CASE WHEN IMGLPT = 'FG07' THEN
CASE
WHEN SDWTUM = 'LB' THEN SDITWT
WHEN UCCONV IS NOT NULL THEN SDITWT*(UCCONV/10000000)
WHEN CONV is not null THEN SDSOQS*CONV*10
ELSE 0 END
ELSE 0
end)/10000 as MDJ_3rdParty_WEIGHT, max(SDCARS) SDCARS
FROM PRODDTA.F42119
left join proddta.F554202x on trim(SDURRF) = trim(TMUSRRSV1) and SDDOCO = TMDOCO
LEFT JOIN PRODDTA.F4101 ON IMITM = SDITM
LEFT JOIN PRODDTA.F41002 ON UMITM = SDITM AND SDMCU = UMMCU AND SDUOM = UMUM AND UMRUM = imuom1
left join PRODDTA.F41003 on UCUM = SDWTUM and UCRUM = 'LB'
Left JOin (SELECT UMMCU as MCU, UMITM as ITM, UMUM as UM, max(CASE WHEN UMRUM = 'LB' THEN UMCONV/10000000 ELSE UMCONV/10000000 * UCCONV/10000000 END) AS CONV
FROM PRODDTA.F41002
LEFT JOIN PRODDTA.F41003
ON UMRUM = UCUM
WHERE (UCRUM = 'LB' OR UMRUM = 'LB')
GROUP BY UMMCU, UMITM, UMUM) CONV2
ON MCU = SDMCU AND ITM = SDITM AND UM = SDUOM
WHERE SDLNTY = 'S'
AND SDSOQS > 0
and not ((SDLTTR = 980 AND SDNXTR = 999) OR SDSOCN = SDUORG)
and SDSRP1 <> 'BLK'
and not exists (select SDDOCO from proddta.F42119 GA where SDADDJ >= FISCALPERIODSTART(14,1) and SDADDJ <= FISCALPERIODEND(14,12) and SDUOM = 'GA' and F42119.SDDOCO = GA.SDDOCO)
and SDDOCO in (1230256,1227461,1230628,1225291,1225297,1231601,1242703,1248671,1249556,1244905)
GROUP BY CASE WHEN NVL(TRIM(TMURRF),' ') = ' ' then SDURRF ELSE TMURRF END) DTL
Left JOIN PRODDTA.F0101 BT ON BT.ABAN8 = DTL.SDAN8
Left JOIN PRODDTA.F0101 ST ON ST.ABAN8 = DTL.SDSHAN
INNER JOIN PRODDTA.F0911 GL
ON TRIM(GL.GLEXR) = TRIM(DTL.SDURRF)
WHERE GLDCT = 'PV' AND GLDGJ >= KIKDATETOJUL(KIKE1JULTODATE(FISCALPERIODSTART(14,1)) - 90) and GLDGJ <= KIKDATETOJUL(KIKE1JULTODATE(FISCALPERIODEND(14,12)) + 90) AND GLOBJ IN ('5025','5026') AND GLLT ='AA' AND GLEXTL <> 'AM' AND GLEXR <> ' ' and GLRE = ' '
GROUP BY GL.GLEXR, GL.GLDCT,
CASE WHEN SDDCTO IN ('ST','SJ') THEN CAST(SDSHAN AS NCHAR(12)) ELSE TRIM(SDMCU) END, DTL.SDASN, DTL.SDDOC, DTL.SDDOCO, DTL.SDDCTO, DTL.SDSOQS, DTL.AER_SDSOQS, DTL.MDJ_SDSOQS, DTL.SDSHAN, DTL.SDAN8, SDURRF, GL.GLSUB, Weight, FG_Weight, AER_WEIGHT, MDJ_WEIGHT, MDJ_3rdParty_WEIGHT
We where provided with the below code to run ahead of the select statement which changes the way the Oracle DB optimizes the query.
alter session set optimizer_index_caching=0;
alter session set optimizer_index_cost_adj=80;
This fixed the issue.

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=,

Got this error and facing a bit because the alias but my head just turning around with stuffs, could you help me to solve the alias wrong check this
SELECT B.PARTS_NO, B.Adj_Date, B.COST, B.ADJ_DESC, ADJ_FG_QTY_PREV = SUM(B.ADJ_FG_QTY_PREV), ADJ_COGS_QTY_PREV = SUM(B.ADJ_COGS_QTYPREV) , ADJ_FG_QTY = SUM(B.ADJ_FG_QTY), ADJ_COGS_QTY = SUM(B.ADJ_COGS_QTY)
FROM
(
SELECT
PARTS_NO=a.PARTS_NO,
Adj_Date=Convert(varchar(10),a.PROCESSING_DATETIME,105),
COST=ISNULL((SELECT CASE WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=1 THEN ISNULL(a.ECOST_01,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=2 THEN ISNULL(a.ECOST_02,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=3 THEN ISNULL(a.ECOST_03,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=4 THEN ISNULL(a.ECOST_04,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=5 THEN ISNULL(a.ECOST_05,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=6 THEN ISNULL(a.ECOST_06,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=7 THEN ISNULL(a.ECOST_07,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=8 THEN ISNULL(a.ECOST_08,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=9 THEN ISNULL(a.ECOST_09,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=10 THEN ISNULL(a.ECOST_10,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=11 THEN ISNULL(a.ECOST_11,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=12 THEN ISNULL(a.ECOST_12,0)
ELSE 0
END
FROM TITEMBALANCE a
WHERE a.[YEAR]=YEAR(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))
AND a.PARTS_NO=a.PARTS_NO),0),
ADJ_DESC ='CATS',
ADJ_FG_QTY_PREV=SUM(CASE WHEN Convert(numeric(6,0),Convert(varchar(6),a.PROCESSING_DATETIME,112))<>ISNULL(a.COSTING1,0) THEN (CASE WHEN Left(Ltrim(b.REASON_CODE),1)='1' THEN b.QUANTITY_F Else 0 End) else 0 end),
ADJ_COGS_QTYPREV=SUM(CASE WHEN Convert(numeric(6,0),Convert(varchar(6),a.PROCESSING_DATETIME,112))<>ISNULL(a.COSTING1,0) THEN (CASE WHEN Left(Ltrim(b.REASON_CODE),1)='2' THEN b.QUANTITY_F Else 0 End) else 0 end),
ADJ_FG_QTY=SUM(CASE WHEN Convert(numeric(6,0),Convert(varchar(6),a.PROCESSING_DATETIME,112))=ISNULL(a.COSTING1,0) THEN (CASE WHEN Left(Ltrim(b.REASON_CODE),1)='1' THEN b.QUANTITY_F Else 0 End) else 0 end),
ADJ_COGS_QTY=SUM(CASE WHEN Convert(numeric(6,0),Convert(varchar(6),a.PROCESSING_DATETIME,112))=ISNULL(a.COSTING1,0) THEN (CASE WHEN Left(Ltrim(b.REASON_CODE),1)='2' THEN b.QUANTITY_F Else 0 End) else 0 end)
FROM TPARTADJUSTMENTC a INNER JOIN TPARTADJUSTMENTCL b ON a.CARD_NO=b.CARD_NO AND a.INHOUSE_OUTSIDE=b.INHOUSE_OUTSIDE AND a.PARTS_NO=b.PARTS_NO AND a.PROCESS_CODE=b.PROCESS_CODE AND a.FILLER=b.FILLER AND a.PROCESSING_DATETIME=b.PROCESSING_DATETIME
WHERE ISNULL(a.COSTING1,0)=Convert(numeric(6,0),#Period)
GROUP BY a.PARTS_NO,Convert(varchar(10),a.PROCESSING_DATETIME,105),Left(Ltrim(b.REASON_CODE),1)
UNION ALL
SELECT
PARTS_NO=a.PARTS_NO,
Adj_Date=Convert(varchar(10),a.PROCESSING_DATETIME,105),
COST=ISNULL((SELECT CASE WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=1 THEN ISNULL(a.ECOST_01,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=2 THEN ISNULL(a.ECOST_02,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=3 THEN ISNULL(a.ECOST_03,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=4 THEN ISNULL(a.ECOST_04,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=5 THEN ISNULL(a.ECOST_05,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=6 THEN ISNULL(a.ECOST_06,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=7 THEN ISNULL(a.ECOST_07,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=8 THEN ISNULL(a.ECOST_08,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=9 THEN ISNULL(a.ECOST_09,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=10 THEN ISNULL(a.ECOST_10,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=11 THEN ISNULL(a.ECOST_11,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=12 THEN ISNULL(a.ECOST_12,0)
ELSE 0
END
FROM TITEMBALANCE a
WHERE a.[YEAR]=YEAR(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))
AND a.PARTS_NO=a.PARTS_NO),0),
ADJ_DESC ='IMPULSE',
ADJ_FG_QTYPREV=SUM(CASE WHEN Convert(numeric(6,0),Convert(varchar(6),a.PROCESSING_DATETIME,112))<>ISNULL(a.COSTING1,0) THEN (CASE WHEN Left(Ltrim(b.REASON_CODE),1)='1' THEN b.QUANTITY_F Else 0 End) else 0 end),
ADJ_COGS_QTYPREV=SUM(CASE WHEN Convert(numeric(6,0),Convert(varchar(6),a.PROCESSING_DATETIME,112))<>ISNULL(a.COSTING1,0) THEN (CASE WHEN Left(Ltrim(b.REASON_CODE),1)='2' THEN b.QUANTITY_F Else 0 End) else 0 end),
ADJ_FG_QTY=SUM(CASE WHEN Convert(numeric(6,0),Convert(varchar(6),a.PROCESSING_DATETIME,112))=ISNULL(a.COSTING1,0) THEN (CASE WHEN Left(Ltrim(b.REASON_CODE),1)='1' THEN b.QUANTITY_F Else 0 End) else 0 end),
ADJ_COGS_QTY=SUM(CASE WHEN Convert(numeric(6,0),Convert(varchar(6),a.PROCESSING_DATETIME,112))=ISNULL(a.COSTING1,0) THEN (CASE WHEN Left(Ltrim(b.REASON_CODE),1)='2' THEN b.QUANTITY_F Else 0 End) else 0 end)
FROM TPARTADJUSTMENTI a INNER JOIN TPARTADJUSTMENTIL b ON a.CARD_NO=b.CARD_NO AND a.INHOUSE_OUTSIDE=b.INHOUSE_OUTSIDE AND a.PARTS_NO=b.PARTS_NO AND a.PROCESS_CODE=b.PROCESS_CODE AND a.FILLER=b.FILLER AND a.PROCESSING_DATETIME=b.PROCESSING_DATETIME
WHERE ISNULL(a.COSTING1,0)=Convert(numeric(6,0),#Period)
GROUP BY a.PARTS_NO,Convert(varchar(10),a.PROCESSING_DATETIME,105),Left(Ltrim(b.REASON_CODE),1)
) B GROUP BY B.PARTS_NO, B.Adj_Date, B.COST, B.ADJ_DESC
You are using the alias a for both TITEMBALANCE in the subquery and TPARTADJUSTMENTC in the query.
I think that the condition a.PARTS_NO=a.PARTS_NO is supposed to compare fields from both tables, but because of the conflicting aliases it will just compare a field to itself and the query will return all parts. That will make the subquery return more than one record, and you get that error message.
This might help the answer, I changed 2 name alias between 2 union. Thanks everyone
SELECT #ProsesPeriode as TanggalPeriod , B.PARTS_NO, B.Adj_Date, B.COST, B.ADJ_DESC, ADJ_FG_QTY_PREV = SUM(B.ADJ_FG_QTY_PREV), ADJ_COGS_QTY_PREV = SUM(B.ADJ_COGS_QTYPREV) , ADJ_FG_QTY = SUM(B.ADJ_FG_QTY), ADJ_COGS_QTY = SUM(B.ADJ_COGS_QTY)
FROM
(
SELECT
PARTS_NO=d.PARTS_NO,
Adj_Date=Convert(varchar(10),d.PROCESSING_DATETIME,105),
COST=ISNULL((SELECT CASE WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=1 THEN ISNULL(a.ECOST_01,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=2 THEN ISNULL(a.ECOST_02,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=3 THEN ISNULL(a.ECOST_03,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=4 THEN ISNULL(a.ECOST_04,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=5 THEN ISNULL(a.ECOST_05,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=6 THEN ISNULL(a.ECOST_06,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=7 THEN ISNULL(a.ECOST_07,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=8 THEN ISNULL(a.ECOST_08,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=9 THEN ISNULL(a.ECOST_09,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=10 THEN ISNULL(a.ECOST_10,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=11 THEN ISNULL(a.ECOST_11,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=12 THEN ISNULL(a.ECOST_12,0)
ELSE 0
END
FROM TITEMBALANCE a
WHERE a.[YEAR]=YEAR(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))
AND a.PARTS_NO=d.PARTS_NO),0),
ADJ_DESC ='CATS',
ADJ_FG_QTY_PREV=SUM(CASE WHEN Convert(numeric(6,0),Convert(varchar(6),d.PROCESSING_DATETIME,112))<>ISNULL(d.COSTING1,0) THEN (CASE WHEN Left(Ltrim(b.REASON_CODE),1)='1' THEN b.QUANTITY_F Else 0 End) else 0 end),
ADJ_COGS_QTYPREV=SUM(CASE WHEN Convert(numeric(6,0),Convert(varchar(6),d.PROCESSING_DATETIME,112))<>ISNULL(d.COSTING1,0) THEN (CASE WHEN Left(Ltrim(b.REASON_CODE),1)='2' THEN b.QUANTITY_F Else 0 End) else 0 end),
ADJ_FG_QTY=SUM(CASE WHEN Convert(numeric(6,0),Convert(varchar(6),d.PROCESSING_DATETIME,112))=ISNULL(d.COSTING1,0) THEN (CASE WHEN Left(Ltrim(b.REASON_CODE),1)='1' THEN b.QUANTITY_F Else 0 End) else 0 end),
ADJ_COGS_QTY=SUM(CASE WHEN Convert(numeric(6,0),Convert(varchar(6),d.PROCESSING_DATETIME,112))=ISNULL(d.COSTING1,0) THEN (CASE WHEN Left(Ltrim(b.REASON_CODE),1)='2' THEN b.QUANTITY_F Else 0 End) else 0 end)
FROM TPARTADJUSTMENTC d INNER JOIN TPARTADJUSTMENTCL b ON d.CARD_NO=b.CARD_NO AND d.INHOUSE_OUTSIDE=b.INHOUSE_OUTSIDE AND d.PARTS_NO=b.PARTS_NO AND d.PROCESS_CODE=b.PROCESS_CODE AND d.FILLER=b.FILLER AND d.PROCESSING_DATETIME=b.PROCESSING_DATETIME
WHERE ISNULL(d.COSTING1,0)=Convert(numeric(6,0),#Period)
GROUP BY d.PARTS_NO,Convert(varchar(10),d.PROCESSING_DATETIME,105),Left(Ltrim(b.REASON_CODE),1)
UNION ALL
SELECT
PARTS_NO=k.PARTS_NO,
Adj_Date=Convert(varchar(10),k.PROCESSING_DATETIME,105),
COST=ISNULL((SELECT CASE WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=1 THEN ISNULL(a.ECOST_01,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=2 THEN ISNULL(a.ECOST_02,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=3 THEN ISNULL(a.ECOST_03,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=4 THEN ISNULL(a.ECOST_04,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=5 THEN ISNULL(a.ECOST_05,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=6 THEN ISNULL(a.ECOST_06,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=7 THEN ISNULL(a.ECOST_07,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=8 THEN ISNULL(a.ECOST_08,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=9 THEN ISNULL(a.ECOST_09,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=10 THEN ISNULL(a.ECOST_10,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=11 THEN ISNULL(a.ECOST_11,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=12 THEN ISNULL(a.ECOST_12,0)
ELSE 0
END
FROM TITEMBALANCE a
WHERE a.[YEAR]=YEAR(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))
AND a.PARTS_NO=k.PARTS_NO),0),
ADJ_DESC ='IMPULSE',
ADJ_FG_QTYPREV=SUM(CASE WHEN Convert(numeric(6,0),Convert(varchar(6),k.PROCESSING_DATETIME,112))<>ISNULL(k.COSTING1,0) THEN (CASE WHEN Left(Ltrim(b.REASON_CODE),1)='1' THEN b.QUANTITY_F Else 0 End) else 0 end),
ADJ_COGS_QTYPREV=SUM(CASE WHEN Convert(numeric(6,0),Convert(varchar(6),k.PROCESSING_DATETIME,112))<>ISNULL(k.COSTING1,0) THEN (CASE WHEN Left(Ltrim(b.REASON_CODE),1)='2' THEN b.QUANTITY_F Else 0 End) else 0 end),
ADJ_FG_QTY=SUM(CASE WHEN Convert(numeric(6,0),Convert(varchar(6),k.PROCESSING_DATETIME,112))=ISNULL(k.COSTING1,0) THEN (CASE WHEN Left(Ltrim(b.REASON_CODE),1)='1' THEN b.QUANTITY_F Else 0 End) else 0 end),
ADJ_COGS_QTY=SUM(CASE WHEN Convert(numeric(6,0),Convert(varchar(6),k.PROCESSING_DATETIME,112))=ISNULL(k.COSTING1,0) THEN (CASE WHEN Left(Ltrim(b.REASON_CODE),1)='2' THEN b.QUANTITY_F Else 0 End) else 0 end)
FROM TPARTADJUSTMENTI k INNER JOIN TPARTADJUSTMENTIL b ON k.CARD_NO=b.CARD_NO AND k.INHOUSE_OUTSIDE=b.INHOUSE_OUTSIDE AND k.PARTS_NO=b.PARTS_NO AND k.PROCESS_CODE=b.PROCESS_CODE AND k.FILLER=b.FILLER AND k.PROCESSING_DATETIME=b.PROCESSING_DATETIME
WHERE ISNULL(k.COSTING1,0)=Convert(numeric(6,0),#Period)
GROUP BY k.PARTS_NO,Convert(varchar(10),k.PROCESSING_DATETIME,105),Left(Ltrim(b.REASON_CODE),1)
) B GROUP BY B.PARTS_NO, B.Adj_Date, B.COST, B.ADJ_DESC
The root cause of your problem with this query is actually conflicting Aliases for Tables ItemBalance & TPartAdjustmentC.
The Same Alias (a) being used for the tables in the union All renders the condition comparing the part numbers as ambiguous.

Using case to choose between two sentences in where clause (Oracle)

im creating a function and i need to choose between two sentences depending on a parameter's value (PTIPO)
Below is my code
SELECT SUM(
CASE PTIPO
WHEN 0 THEN (CASE WHEN (A.NT = 0) THEN A.VALOR ELSE 0 END)
WHEN 1 THEN (CASE WHEN (A.NT = 1) THEN A.VALOR ELSE 0 END)
WHEN 2 THEN (CASE WHEN (A.NT = 1) THEN A.VALOR ELSE -A.VALOR END)
END)
INTO nresp
FROM mov_caja a
JOIN enc_movp b ON a.docid = b.docid
JOIN c_caja c ON a.cajaid = c.cajaid
WHERE c.cajaid = pcajaid AND(
CASE WHEN(PTIPO = 2) --this is what causes the issue.
THEN
b.cod_compro = ncompini OR (b.fecha_mov BETWEEN pfecha_ini AND pfecha_fin)
ELSE
b.cod_compro != ncompini AND b.fecha_mov BETWEEN pfecha_ini AND pfecha_fin
END);
The error is "missing keyword", but i know the problem is the last CASE.
How else could i select between the sentences. Is the case a proper way or should i use another statement ?
A case can return a value, but not an expression. This should do the trick, although I feel it could even be simpler:
SELECT SUM(
CASE PTIPO
WHEN 0 THEN (CASE WHEN (A.NT = 0) THEN A.VALOR ELSE 0 END)
WHEN 1 THEN (CASE WHEN (A.NT = 1) THEN A.VALOR ELSE 0 END)
WHEN 2 THEN (CASE WHEN (A.NT = 1) THEN A.VALOR ELSE -A.VALOR END)
END)
INTO nresp
FROM mov_caja a
JOIN enc_movp b ON a.docid = b.docid
JOIN c_caja c ON a.cajaid = c.cajaid
WHERE
c.cajaid = pcajaid AND
(
(PTIPO = 2 and (b.cod_compro = ncompini OR b.fecha_mov BETWEEN pfecha_ini AND pfecha_fin))
OR
(PTIPO <> 2 and (b.cod_compro != ncompini AND b.fecha_mov BETWEEN pfecha_ini AND pfecha_fin))
)
Try this:
WHERE c.cajaid = pcajaid AND
(
PTIPO = 2
AND (
b.cod_compro = ncompini
OR b.fecha_mov BETWEEN pfecha_ini AND pfecha_fin
)
OR
PTIPO != 2
AND (
b.cod_compro != ncompini
AND b.fecha_mov BETWEEN pfecha_ini AND pfecha_fin
)
)