newbie oracle update statement error - sql

oracle query:
UPDATE AIRMODEL_NETWORK_SUMMARY
SET CASES_PRODUCED = (SELECT DISTINCT PRDCTN_RUN_ACTL_CASE_QTY
FROM AIRMODEL_NETWORK_SUMMARY, HISTORY_PRODUCTION, PERIOD_TO_PROCESS
WHERE AIRMODEL_NETWORK_SUMMARY.FSCL_WK_IN_YR_NUM = HISTORY_PRODUCTION.FSCL_WK_IN_YR_NUM
AND AIRMODEL_NETWORK_SUMMARY.FSCL_YR_NUM = HISTORY_PRODUCTION.FSCL_YR_NUM
AND AIRMODEL_NETWORK_SUMMARY.LOC_ID = HISTORY_PRODUCTION.LOC_ID
AND HISTORY_PRODUCTION.FSCL_WK_IN_YR_NUM = PERIOD_TO_PROCESS.FSCL_WK_IN_YR_NUM
AND HISTORY_PRODUCTION.FSCL_YR_NUM = PERIOD_TO_PROCESS.FSCL_YR_NUM);
is returning the following error:
ORA-01427: single-row subquery returns more than one row
Another attempt at correction:
MERGE INTO AIRMODEL_NETWORK_SUMMARY AIRMODEL_NETWORK_SUMMARY1
USING (SELECT DISTINCT PRDCTN_RUN_ACTL_CASE_QTY,
AIRMODEL_NETWORK_SUMMARY2.rowid AS r
FROM AIRMODEL_NETWORK_SUMMARY AIRMODEL_NETWORK_SUMMARY2
INNER JOIN HISTORY_PRODUCTION
ON AIRMODEL_NETWORK_SUMMARY2.FSCL_WK_IN_YR_NUM = HISTORY_PRODUCTION.FSCL_WK_IN_YR_NUM
AND AIRMODEL_NETWORK_SUMMARY2.FSCL_YR_NUM = HISTORY_PRODUCTION.FSCL_YR_NUM
AND AIRMODEL_NETWORK_SUMMARY2.LOC_ID = HISTORY_PRODUCTION.LOC_ID
INNER JOIN PERIOD_TO_PROCESS
ON HISTORY_PRODUCTION.FSCL_WK_IN_YR_NUM = PERIOD_TO_PROCESS.FSCL_WK_IN_YR_NUM
AND HISTORY_PRODUCTION.FSCL_YR_NUM = PERIOD_TO_PROCESS.FSCL_YR_NUM)
ON (AIRMODEL_NETWORK_SUMMARY1.rowid = r)
WHEN MATCHED THEN UPDATE
SET CASES_PRODUCED = PRDCTN_RUN_ACTL_CASE_QTY;
returns the following error:
ORA-30926: unable to get a stable set of rows in the source tables
I am a noob and need help :(
thank you.

You can assign only a single, scalar value to CASES_PRODUCED. So your subquery needs to produce only a single, scalar value.
You need to find why your subquery returns more than one row.
SELECT DISTINCT ... will select unique rows, not the same as ONE ROW.
Do you need the sum total of all the PRDCTN_RUN_ACTL_CASE_QTY in the rows?
Or the average?
Or the MAX number?
Or the first row?
Use an aggregate function if so:
Total
UPDATE AIRMODEL_NETWORK_SUMMARY
SET CASES_PRODUCED = (SELECT SUM(PRDCTN_RUN_ACTL_CASE_QTY) ...
Max
UPDATE AIRMODEL_NETWORK_SUMMARY
SET CASES_PRODUCED = (SELECT MAX(PRDCTN_RUN_ACTL_CASE_QTY) ...
Average
UPDATE AIRMODEL_NETWORK_SUMMARY
SET CASES_PRODUCED = (SELECT AVG(PRDCTN_RUN_ACTL_CASE_QTY) ...
First row
UPDATE AIRMODEL_NETWORK_SUMMARY
SET CASES_PRODUCED = (SELECT PRDCTN_RUN_ACTL_CASE_QTY ...
FROM ...
WHERE ROWNUM = 1)
It is critical, especially when learning, and struggling with syntax, that you clearly understand
What you need from the query
What your query is returning
Just trying a bunch of alternatives until you get success is a sure fire way to create erroneous data that seems to work.
My suggestion is to first copy the subquery SELECT to a different window and run it, view and understand the results. It should be clear that it is a multi-row result. Work with the subquery until it is returning a correct, single result, then plug it back into the larger update.

Related

MS Access SQL Update with Minimum

This SQL is beyond my expertise. I think it should be fairly easy for someone with experience. Here is what I have so far..
SQL is as follows:
UPDATE (Tbl_Stg_Project_Schedule_Dates
INNER JOIN Tbl_Child_ITN ON Tbl_Stg_Project_Schedule_Dates.ms_itn = Tbl_Child_ITN.ITN)
INNER JOIN Tbl_Schedule ON Tbl_Child_ITN.Id = Tbl_Schedule.ID SET Tbl_Schedule.a_construction_start = [Tbl_Stg_Project_Schedule_Dates].[ms_start_date]
WHERE (((Tbl_Stg_Project_Schedule_Dates.ms_tempt_id) In (16,17,18,19,20,21,22,23)));
I want to add one last condition to this being that I only want the minimum of [Tbl_Stg_Project_Schedule_Dates].[ms_start_date] to update the table. I've tried the obvious of wrapping the field in Min, and also tried creating a separate aggregate select statement first (to get the min value with other criteria) that I then tried to create the update query from in new query but no luck.
I believe this is valid Access/Jet SQL. The idea here is to use a subquery to look up the earliest date among all the rows in your subset. I'm not sure if ms_itn was the right column to correlate on but hopefully you get the idea:
UPDATE (Tbl_Stg_Project_Schedule_Dates
INNER JOIN Tbl_Child_ITN ON Tbl_Stg_Project_Schedule_Dates.ms_itn = Tbl_Child_ITN.ITN)
INNER JOIN Tbl_Schedule ON Tbl_Child_ITN.Id = Tbl_Schedule.ID
SET Tbl_Schedule.a_construction_start = [Tbl_Stg_Project_Schedule_Dates].[ms_start_date]
WHERE (((Tbl_Stg_Project_Schedule_Dates.ms_tempt_id) In (16,17,18,19,20,21,22,23)))
and [Tbl_Stg_Project_Schedule_Dates].[ms_start_date] = (
select min(sd.[ms_start_date])
from [Tbl_Stg_Project_Schedule_Dates] as sd
where sd.ms_itn = [Tbl_Stg_Project_Schedule_Dates].ms_itn
)

single-row subquery returns more than one row. Query not working with main query

I hve to display several cell values into one cell. So I am using this query:
select LISTAGG(fc.DESCRIPTION, ';'||chr(10))WITHIN GROUP (ORDER BY fc.SWITCH_NAME) AS DESCRIP from "ORS".SWITCH_OPERATIONS fc
group by fc.SWITCH_NAME
It is working fine. But when I am merging this with my main(complete) query then I am getting the error as: Error code 1427, SQL state 21000: ORA-01427: single-row subquery returns more than one row
Here is my complete query:
SELECT
TRACK_EVENT.LOCATION,
TRACK_EVENT.ELEMENT_NAME,
(select COUNT(*) from ORS.TRACK_EVENT b where (b.ELEMENT_NAME = sw.SWITCH_NAME)AND (b.ELEMENT_TYPE = 'SWITCH')AND (b.EVENT_TYPE = 'I')AND (b.ELEMENT_STATE = 'NORMAL' OR b.ELEMENT_STATE = 'REVERSE'))as COUNTER,
(select COUNT(*) from ORS.SWITCH_OPERATIONS fc where TRACK_EVENT.ELEMENT_NAME = fc.SWITCH_NAME and fc.NO_CORRESPONDENCE = 1 )as FAIL_COUNT,
(select MAX(cw.COMMAND_TIME) from ORS.SWITCH_OPERATIONS cw where ((TRACK_EVENT.ELEMENT_NAME = cw.SWITCH_NAME) and (cw.NO_CORRESPONDENCE = 1)) group by cw.SWITCH_NAME ) as FAILURE_DATE,
(select LISTAGG(fc.DESCRIPTION, ';'||chr(10))WITHIN GROUP (ORDER BY fc.SWITCH_NAME) AS DESCRIP from "ORS".SWITCH_OPERATIONS fc
group by fc.SWITCH_NAME)
FROM
ORS.SWITCH_OPERATIONS sw,
ORS.TRACK_EVENT TRACK_EVENT
WHERE
sw.SEQUENCE_ID = TRACK_EVENT.SEQUENCE_ID
Not only are subqueries in the SELECT list required to return exactly one row (or any time they're used for a singular comparison, like <, =, etc), but their use in that context tends to make the database execute them RBAR - Row-by-agonizing-row. That is, they're slower and consume more resources than they should.
Generally, unless the result set outside the subquery contains only a few rows, you want to construct subqueries as part of a table-reference. Ie, something like:
SELECT m.n, m.z, aliasForSomeTable.a, aliasForSomeTabe.bSum
FROM mainTable m
JOIN (SELECT a, SUM(b) AS bSum
FROM someTable
GROUP BY a) aliasForSomeTable
ON aliasForSomeTable.a = m.a
This benefits you in other ways to - it's easier to get multiple columns out of the same table-reference, for example.
Assuming that LISTAGG(...) can be included with other aggregate functions, you can change your query to look like this:
SELECT Track_Event.location, Track_Event.element_name,
Counted_Events.counter,
Failure.fail_count, Failure.failure_date, Failure.descrip
FROM ORS.Track_Event
JOIN ORS.Switch_Operations
ON Switch_Operations.sequence_id = Track_Event.sequence_id
LEFT JOIN (SELECT element_name, COUNT(*) AS counter
FROM ORS.Track_Event
WHERE element_type = 'SWITCH'
AND event_type = 'I'
AND element_state IN ('NORMAL', 'REVERSE')
GROUP BY element_name) Counted_Events
ON Counted_Events.element_name = Switch_Operations.swicth_name
LEFT JOIN (SELECT switch_name,
COUNT(CASE WHEN no_correspondence = 1 THEN '1' END) AS fail_count,
MAX(CASE WHEN no_correspondence = 1 THEN command_time END) AS failure_date,
LISTAGG(description, ';' || CHAR(10)) WITHIN GROUP (ORDER BY command_time) AS descrip
FROM ORS.Switch_Operations
GROUP BY switch_name) Failure
ON Failure.switch_name = Track_Event.element_name
This query was written to (attempt to) preserve the semantics of your original query. I'm not completely sure that's what you actually need but without sample starting data and desired results, I have no way to tell how else to improve this. For instance, I'm a little suspicious of the need of Switch_Operations in the outer query, and the fact that LISTAGG(...) is run over row where no_correspondence <> 1. I did change the ordering of LISTAGG(...), because the original column would not have done anything (because the order way the same as the grouping), so would not have been a stable sort.
Single-row subquery returns more than one row.
This error message is self descriptive.
Returned field can't have multiple values and your subquery returns more than one row.
In your complete query you specify fields to be returned. The last field expects single value from the subquery but gets multiple rows instead.
I have no clue about the data you're working with but either you have to ensure that subquery returns only one row or you have to redesign the wrapping query (possibly using joins when appropriate).

SQL - updating Oracle 10g database from a complex query

trying to update a single column based on criteria. The rows that need to be updated are returned by the query
SELECT
it.objectid,
it.versionnumber,
it.itemnumber "Item Number",
it.itemtype,
itcovprem.basisofsettlement,
itcovprem.coverage "Coverage"
FROM
itemcoveragesandpremiums itcovprem,
items it,
policies pl
WHERE
pl.objectid = it.parentobjectid AND
pl.policytype in ('H','F') AND
it.objectid = itcovprem.itemobjectid AND
it.itemtype in ('SHOA','SHOB','SHOC','SHOD','SHOK','SHOL') and
it.versionnumber = itcovprem.itemversionnumber AND
((itcovprem.coverage like ('A - Dwg Bldg%')) or
(itcovprem.coverage like ('#42 - Repl Cost Plus%')) or
(itcovprem.coverage like ('#42 - Limited GRC%'))) and
it.effectivedate >= TO_DATE('01-JAN-2006', 'DD-MON-YYYY') and
exists (select * from itemcoveragesandpremiums icp where icp.itemobjectid = it.objectid and icp.itemversionnumber = it.versionnumber and icp.coverage like ('#42%')) and
itcovprem.basisofsettlement not in ('LGRC')
I've tried a few options to convert this to an update query, but no joy.
I get Error - line 3 - SQL command not properly ended when using
update itemcoveragesandpremiums
set basisofsettlement = 'LGRC'
from itemcoveragesandpremiums as itcovprem
inner join items as it
on it.objectid = itcovprem.itemobjectid and it.versionnumber = itcovprem.itemversionnumber
inner join policies as pl
on pl.objectid = it.parentobjectid
where [cut, rest of query was below]
I get Error - line 6 - missing right parenthesis when trying use an inline query
update
(
SELECT
itcovprem.basisofsettlement as OLD
FROM
itemcoveragesandpremiums as itcovprem inner join items as it on it.objectid = itcovprem.itemobjectid and it.versionnumber = itcovprem.itemversionnumber inner join policies AS pl on pl.objectid = it.parentobjectid
WHERE [query snipped]
) t
set t.old = 'LGRC'
Seems that SQL*Plus just wants to stop looking at the update before it gets to the meat of my select query. I'm not sure if I'm formatting it incorrectly or going at it from the wrong direction. Any advice?
In your first attempt, the error at line 3 is because update doesn't support a from or join clause. In your second attempt the immediate error at line 6 is because you're trying to alias a table with as itcovprem; but you can only use as for column aliases, not for table aliases. (The first attempt is trying to do that too, but it isn't getting as far as encountering that problem). But you can't generally update an inline-view with joins anyway, so it would still error with that - something like an ORA-01779.
You would need to do something like:
update itemcoveragesandpremiums
set basisofsettlement = 'LGRC'
where (itemobjectid, itemversionnumber, basisofsettlement, coverage) in (
select it.objectid,
it.versionnumber,
itcovprem.basisofsettlement,
itcovprem.coverage
from ...
)
Assuming that itemobjectid, itemversionnumber, basisofsettlement, coverage identifies a row sufficiently such that you don't risk updating anything you shouldn't. It might be safer to add a rowid to the select and use that for the update instead to avoid ambiguity:
update itemcoveragesandpremiums
set basisofsettlement = 'LGRC'
where rowid in (
select itcovprem.rowid as target_rowid
from ...
)

Gettin a value from a table and using in the same query

SELECT (h.horario), h.codigo
FROM horarios as h
JOIN horario_turma as h_t
ON(h.codigo != h_t.cd_horario)
WHERE h_t.cd_turma = 'HTJ009'
AND h_t.cd_dia = 2
AND h.cd_turno = 1
I'm trying to figure out if there's a possibility to get the h.cd_turnovalue from another table and use in the same query, beacuse this value is gonna be variable. So, I'd have to get this value from a query, then pass the value to PHP and do another query with this value. Is there a way to do that in the same query?
There's a table called turmas(codigo, cd_turno). I'll have the codigovalue, in this case HTJ009, and I'd like to select the cd_turno value.
Query used to get the value:
SELECT cd_turno FROM turmas WHERE codigo='HTJ009'
You can use a subquery, like so:
SELECT (h.horario), h.codigo
FROM horarios as h
JOIN horario_turma as h_t
ON(h.codigo != h_t.cd_horario)
WHERE h_t.cd_turma = 'HTJ009'
AND h_t.cd_dia = 2
AND h.cd_turno = (SELECT cd_turno FROM turmas WHERE codigo='HTJ009')
In this case, remember that it is important for the subquery to return only one result, otherwise you'll encounter an error. If you do see such an error, you may have to tweak the subquery to ensure only one result is returned.
Check this out for Postgres subquery documentation
SELECT (h.horario), h.codigo
FROM horarios as h
JOIN horario_turma as h_t
ON(h.codigo = h_t.cd_horario)
WHERE h_t.cd_turma = 'HTJ009'
AND h_t.cd_dia = 2
AND h.cd_turno = 1 and h_t.cd_horario is null

MAX Subquery in SQL Anywhere Returning Error

In sqlanywhere 12 I wrote the following query which returns two rows of data:
SELECT "eDatabase"."Vendor"."VEN_CompanyName", "eDatabase"."OrderingInfo"."ORD_Timestamp"
FROM "eDatabase"."OrderingInfo"
JOIN "eDatabase"."Vendor"
ON "eDatabase"."OrderingInfo"."ORD_VEN_FK" = "eDatabase"."Vendor"."VEN_PK"
WHERE ORD_INV_FK='7853' AND ORD_DefaultSupplier = 1
Which returns:
'**United Natural Foods IN','2018-02-07 15:05:15.513'
'Flora ','2018-02-07 14:40:07.491'
I would like to only return the row with the maximum timestamp in the column "ORD_Timestamp". After simply trying to select by MAX("eDatabase"."OrderingInfo"."ORD_Timestamp") I found a number of posts describing how that method doesn't work and to use a subquery to obtain the results.
I'm having difficulty creating the subquery in a way that works and with the following query I'm getting a syntax error on my last "ON":
SELECT "eDatabase"."Vendor"."VEN_CompanyName", "eDatabase"."OrderingInfo"."ORD_Timestamp"
FROM ( "eDatabase"."OrderingInfo"
JOIN
"eDatabase"."OrderingInfo"
ON "eDatabase"."Vendor"."VEN_PK" = "eDatabase"."OrderingInfo"."ORD_VEN_FK" )
INNER JOIN
(SELECT "eDatabase"."Vendor"."VEN_CompanyName", MAX("eDatabase"."OrderingInfo"."ORD_Timestamp")
FROM "eDatabase"."OrderingInfo")
ON "eDatabase"."Vendor"."VEN_PK" = "eDatabase"."OrderingInfo"."ORD_VEN_FK"
WHERE ORD_INV_FK='7853' AND ORD_DefaultSupplier = 1
Does anyone know how I can adjust this to make the query correctly select only the max ORD_Timestamp row?
try this:
SELECT TOP 1 "eDatabase"."Vendor"."VEN_CompanyName", "eDatabase"."OrderingInfo"."ORD_Timestamp"
FROM "eDatabase"."OrderingInfo"
JOIN "eDatabase"."Vendor"
ON "eDatabase"."OrderingInfo"."ORD_VEN_FK" = "eDatabase"."Vendor"."VEN_PK"
WHERE ORD_INV_FK='7853' AND ORD_DefaultSupplier = 1
order by "ORD_Timestamp" desc
this orders them biggest on to and say only hsow the top row