Oracle (Netsuite) SQL one join limit results - sql

I have an oracle SQL query and a slight problem. I need to check if an item has a PO# that it has at least 1 line item. The query below works however it returns a result for each line of transaction_lines and I need only une result. PS I tried DISTINCT but get an ODBC error.
SELECT ITEMS.NAME, INVENTORY_NUMBER.INVENTORY_NUMBER, INVENTORY_NUMBER.ON_HAND_COUNT, ITEMS.SALESDESCRIPTION, CONDITION.LIST_ITEM_NAME,
BRAND_PARTNER.LIST_ITEM_NAME, PPROGRAM.LIST_ITEM_NAME, ENTITY.NAME, PO.TRANSACTION_NUMBER, INVENTORY_NUMBER.RECEIVED_COST, ITEMS.SALESPRICE, IR.TRANSACTION_NUMBER,
INVENTORY_SOURCE.LIST_ITEM_NAME, LOCATIONS.NAME, INVENTORY_NUMBER.RECEIPT_DATE, PO.INTERNAL_MEMO, INVENTORY_NUMBER.REFERENCE_, TEST_RESULTS.LIST_ITEM_NAME,
INVENTORY_NUMBER.TEST_FILE_LINK, INVENTORY_NUMBER.CONNECT_TRADE_ID, INVENTORY_NUMBER.SOLD_DATE, INVENTORY_NUMBER.SOLD_PRICE, INVENTORY_NUMBER.MEMO, ITEMS.UPC_CODE, ITEMS.MPN,
ITEMS.ITEM_ID, INVENTORY_NUMBER.CLEI, INVENTORY_NUMBER.CERTIFICATION_REF_ID
FROM INVENTORY_NUMBER
INNER JOIN ITEMS ON INVENTORY_NUMBER.ITEM_ID = ITEMS.ITEM_ID
INNER JOIN TRANSACTIONS AS PO ON INVENTORY_NUMBER.PURCHASE_ORDER_ID = PO.TRANSACTION_ID
INNER JOIN TRANSACTIONS AS IR ON INVENTORY_NUMBER.ITEM_RECEIPT_ID = IR.TRANSACTION_ID
INNER JOIN TRANSACTION_LINES ON PO.TRANSACTION_ID = TRANSACTION_LINES.TRANSACTION_ID
INNER JOIN ENTITY ON TRANSACTIONS.ENTITY_ID = ENTITY.ENTITY_ID
INNER JOIN CONDITION ON INVENTORY_NUMBER.CONDITION_ID = CONDITION.LIST_ID
INNER JOIN BRAND_PARTNER ON INVENTORY_NUMBER.BRAND_PARTNER_ID = BRAND_PARTNER.LIST_ID
INNER JOIN PPROGRAM ON INVENTORY_NUMBER.PROGRAM_ID = PPROGRAM.LIST_ID
INNER JOIN INVENTORY_SOURCE ON INVENTORY_NUMBER.INVENTORY_SOURCE_ID = INVENTORY_SOURCE.LIST_ID
INNER JOIN LOCATIONS ON INVENTORY_NUMBER.LOCATION_ID = LOCATIONS.LOCATION_ID
INNER JOIN TEST_RESULTS ON INVENTORY_NUMBER.TEST_RESULTS_ID = TEST_RESULTS.LIST_ID
WHERE INVENTORY_NUMBER.ON_HAND_COUNT IS NOT NULL AND ((INVENTORY_NUMBER.PURCHASE_ORDER_ID IS NULL) OR (INVENTORY_NUMBER.PURCHASE_ORDER_ID IS NOT NULL AND TRANSACTION_LINES.TRANSACTION_LINE_ID IS NOT NULL))

you could also remove the join to the transaction_lines and instead of tl.TRANSACTION_LINE_ID IS NOT NULL use an exists clause
and exists (select 1 from transaction lines tl
where tl.transaction_id = po.transaction_id)

I would suggest using a GROUP BY to help limit your results. You could also if you are interacting with transactions in your query you must always remember that without limiting results based on the "main line" you will receive the header record and then a record for each individual line item.
If you were doing this with a saved search you could put the criteria as "main line = true". Since I don't understand your query entirely I can't advise where to put this limitation in.

Related

Subquery returned more than 1 value - Error Message

I'm getting the error message:
Subquery returned more than 1 value. This is not permitted when the subquery follows =,!=,<,<=,>,=> or when the subquery is used as an expression.
Below is a small subset of a larger query, but the part of the query to determine the Test_Col value is essentially where I'm running into this issue. The query by itself works, but when I use it as a subquery within the larger query, I get this error message in SQL Server. Any ideas on where I'm going wrong?
select
distinct(nml.scode) Loan_Num,
(select isnull(sum(isnull(t.smtd, 0) + isnull(t.sbeginbudget, 0)), 0)
from nmloan nml
left join property p on nml.hprop = p.hmy
left join total t on p.hmy = t.hppty
where nml.hprop in (2380, 3348)
and t.umonth between '1/1/1900' and '9/30/2021'
and t.ibook = 1 and t.hacct in (1349, 1348, 1347, 1345, 1343, 1342, 1341, 1339, 1338, 1337, 1336, 1334, 1332, 1690, 1682, 1331)
group by nml.hprop) Test_Col
from
nmloan nml
left join
property p on nml.hprop = p.hmy
left join
total t on p.hmy = t.hppty
left join
acct ac on ac.hmy = t.hacct
left join
nmborrower nmb on nml.hmy = nmb.hnmloan
left join
person ps on nmb.hmyperson = ps.hmy
left join
nmloanterms nmt on nml.hmy = nmt.hloan
left join
nmcollateralxref nmx on nml.hmy = nmx.hnmloan
left join
nmcollateral nmc on nmx.hnmcollateral = nmc.hmy
left join
loanbut1 lb1 on nml.hmy = lb1.hcode
left join
NMLedger l ON nml.hmy = l.hNMLoan
left join
nmLedgerDetail d on l.hmy = d.hNMLedger
left join
loanbut7 lb on nml.hmy = lb.hcode
left join
loanbut8 lb8 on nml.hmy = lb8.hcode
left join
loanbut9 lb9 on nml.hmy = lb9.hcode
where
nml.hprop in (2380, 3348)
and lb.lrPeriod in ('9/30/2021')
and lb9.lrnDate in ('9/30/2021')
group by
nml.hprop, nml.scode
In SQL Server DB if your subquery is written after the select command where we wrote field name list, then your subquery must be return only one record and only one field, else you will get an error. In your script, you wrote subquery before the from command, after this Loan_Num,. I did a little research on your subquery. Your subquery will return more than 1 record in most cases. The reason is that you wrote group by nml.hprop and after the where command you wrote this condition nml.hprop in (2380, 3348). I would have written this query for you myself, but I don't know your business logic and what need you. If your subquery must return more than 1 record, so you must join this subquery to the main query, using inner join or left join, you can not write this subquery on the field list.
Turns out that since my subquery's alias, nml, has the same alias as the parent query, nml (for the nmLoan table), it was did not work.
Upon changing my subquery's alias to nl and leaving the parent query's alias to nml, that actually worked and I was able to generate multiple results.

Cannot get both records with SQL/Bigquery JOINs

I've got a query that returns order details, I want information from the briisk table for deals it has found. I also want it to display orders even if the briisk table has nothing.
If I add the final line (and flostream.briisk.master = "") my query only returns one result instead of two.
SELECT *
FROM (SELECT orderno,ifnull(dealid,sales_rule) as DealIDCombo from flostream.orders left join mobileheads.surveys on mobileheads.surveys.order_number = flostream.orders.externalreference) as first
INNER JOIN flostream.orders on first.orderno = flostream.orders.orderno
LEFT JOIN flostream.briisk on first.dealidcombo = flostream.briisk.uniquereference
WHERE first.orderno in (359692,359683)
//AND flostream.briisk.master = ""
When you use a left outer join, then you need to include filter conditions on the second table in the on clause. So try this:
SELECT *
FROM (SELECT orderno,ifnull(dealid,sales_rule) as DealIDCombo
from flostream.orders left join
mobileheads.surveys
on mobileheads.surveys.order_number = flostream.orders.externalreference
) as first INNER JOIN
flostream.orders
on first.orderno = flostream.orders.orderno LEFT JOIN
flostream.briisk
on first.dealidcombo = flostream.briisk.uniquereference AND
flostream.briisk.master = ""
WHERE first.orderno in (359692, 359683)
Conditions on the first table should go in the WHERE clause.

SQL Query to retrieve single record per filter

I have the following query:
SELECT min(salesorder.SOM_SalesOrderID) AS salesorder,
Item.IMA_ItemID,
Item.IMA_ItemName,
Customer.CUS_CorpName,
WK.WKO_WorkOrderID,
min(WK.WKO_OrigRequiredDate),
WK.WKO_WorkOrderTypeCode,
min(WK.WKO_RequiredDate),
max(WK.WKO_LastWorkDate),
min(wk.WKO_RequiredQty),
wk.WKO_MatlIssueDate,
min(SalesOrderDelivery.SOD_RequiredQty),
Item.IMA_ItemTypeCode,
Item.IMA_OnHandQty,
min(SalesOrderDelivery.SOD_PromiseDate),
min(WO.woo_operationseqID) AS seqid
FROM SalesOrder
INNER JOIN SalesOrderLine ON SalesOrder.SOM_RecordID = SalesOrderLine.SOI_SOM_RecordID
INNER JOIN SalesOrderDelivery ON SalesOrderLine.SOI_RecordID = SalesOrderDelivery.SOD_SOI_RecordID,
WO.
INNER JOIN Item ON SalesOrderLine.SOI_IMA_RecordID = Item.IMA_RecordID
INNER JOIN WKO wk ON Item.IMA_ItemID = WK.WKO_ItemID
INNER JOIN Customer ON SalesOrder.SOM_CUS_RecordID = Customer.CUS_RecordID
INNER JOIN woo WO ON WO.WOO_WorkOrderID = WK.WKO_WorkOrderID
WHERE wk.WKO_StatusCode = 'Released'
AND WO.WOO_StatusCode IS NULL
AND SalesOrderDelivery.SOD_ShipComplete = 'false'
GROUP BY WK.WKO_WorkOrderID,
Item.IMA_ItemID,
Item.IMA_ItemName,
Customer.CUS_CorpName,
WK.WKO_WorkOrderTypeCode,
wk.WKO_MatlIssueDate,
Item.IMA_ItemTypeCode,
Item.IMA_OnHandQty
I need 1 record returned for each wk.wko_workorderid. There is a field that is not included that I'm not sure how to get. I need to retrieve the woo.woo_workcenterid that corresponds to min(WO.woo_operationseqID)as seqid. I cannot include it in the general query since there are multiple workcenterids in the table and I only want the specific one that is part of the min operation sequence record.
Any help would be appreciated.

Ambiguous outer join in MS Access

Trying to create an outer join on two other joined tables when recieving this error - I just dont see how to create two separate queries to make it work. Subqueries don't seem to work either, any help appreciated. I get errors for the below query, thanks.
SELECT
CardHeader.CardID, CardHeader.CardDescription, CardHeader.GloveSize,
CardHeader.GloveDescription, CardDetail.Bin, CardDetail.ItemID, Items.ItemDescription,
Items.VCatalogID, CardDetail.ChargeCode, CardDetail.Quantity, Items.Cost, CardColors.ColorID
FROM
((Items
INNER JOIN
(CardHeader INNER JOIN CardDetail ON CardHeader.CardID = CardDetail.CardID) ON Items.ItemID = CardDetail.ItemID)
LEFT JOIN
CardColors ON CardDetail.ItemID = CardColors.ItemID)
INNER JOIN
Colors ON CardColors.ColorID = Colors.ID
ORDER BY
CardHeader.CardID;
I tried the following which runs but asks for the following parameters (which it shouldnt)
CardHeader.ID, MainQry.CardID
SELECT
MainQry.ID, MainQry.CardDescription, MainQry.GloveSize,
MainQry.GloveDescription, MainQry.Bin, MainQry.ItemID,
MainQry.ItemDescription, MainQry.VCatalogID, MainQry.ChargeCode,
MainQry.Quantity, MainQry.Cost, SubQry.ColorID
FROM
(SELECT
CardHeader.ID, CardHeader.CardDescription, CardHeader.GloveSize,
CardHeader.GloveDescription, CardDetail.Bin,
CardDetail.ItemID, Items.ItemDescription, Items.VCatalogID,
CardDetail.ChargeCode, CardDetail.Quantity, Items.Cost
FROM
Items
INNER JOIN
(CardHeader
INNER JOIN
CardDetail ON CardHeader.CardID = CardDetail.CardID) ON Items.ItemID = CardDetail.ItemID
) AS MainQry
LEFT JOIN
(SELECT
CardColors.ItemID, CardColors.ColorID
FROM
CardColors
INNER JOIN
Colors ON CardColors.ColorID = Colors.ID) AS SubQry ON MainQry.ItemID = SubQry.ItemID
ORDER BY
MainQry.CardID;
The second SQL statement can be corrected by reference to the first statement and the error. The error is that both CardHeader.ID and MainQry.CardID are prompting for a parameter, which indicates that the inner statement should include CardHeader.CardID, rather than CardHeader.ID

Super Slow Query - sped up, but not perfect... Please help

I posted a query yesterday (see here) that was horrible (took over a minute to run, resulting in 18,215 records):
SELECT DISTINCT
dbo.contacts_link_emails.Email, dbo.contacts.ContactID, dbo.contacts.First AS ContactFirstName, dbo.contacts.Last AS ContactLastName, dbo.contacts.InstitutionID,
dbo.institutionswithzipcodesadditional.CountyID, dbo.institutionswithzipcodesadditional.StateID, dbo.institutionswithzipcodesadditional.DistrictID
FROM
dbo.contacts_def_jobfunctions AS contacts_def_jobfunctions_3
INNER JOIN
dbo.contacts
INNER JOIN
dbo.contacts_link_emails
ON dbo.contacts.ContactID = dbo.contacts_link_emails.ContactID
ON contacts_def_jobfunctions_3.JobID = dbo.contacts.JobTitle
INNER JOIN
dbo.institutionswithzipcodesadditional
ON dbo.contacts.InstitutionID = dbo.institutionswithzipcodesadditional.InstitutionID
LEFT OUTER JOIN
dbo.contacts_def_jobfunctions
INNER JOIN
dbo.contacts_link_jobfunctions
ON dbo.contacts_def_jobfunctions.JobID = dbo.contacts_link_jobfunctions.JobID
ON dbo.contacts.ContactID = dbo.contacts_link_jobfunctions.ContactID
WHERE
(dbo.contacts.JobTitle IN
(SELECT JobID
FROM dbo.contacts_def_jobfunctions AS contacts_def_jobfunctions_1
WHERE (ParentJobID <> '1841')))
AND
(dbo.contacts_link_emails.Email NOT IN
(SELECT EmailAddress
FROM dbo.newsletterremovelist))
OR
(dbo.contacts_link_jobfunctions.JobID IN
(SELECT JobID
FROM dbo.contacts_def_jobfunctions AS contacts_def_jobfunctions_2
WHERE (ParentJobID <> '1841')))
AND
(dbo.contacts_link_emails.Email NOT IN
(SELECT EmailAddress
FROM dbo.newsletterremovelist AS newsletterremovelist))
ORDER BY EMAIL
With a lot of coaching and research, I've tuned it up to the following:
SELECT contacts.ContactID,
contacts.InstitutionID,
contacts.First,
contacts.Last,
institutionswithzipcodesadditional.CountyID,
institutionswithzipcodesadditional.StateID,
institutionswithzipcodesadditional.DistrictID
FROM contacts
INNER JOIN contacts_link_emails ON
contacts.ContactID = contacts_link_emails.ContactID
INNER JOIN institutionswithzipcodesadditional ON
contacts.InstitutionID = institutionswithzipcodesadditional.InstitutionID
WHERE
(contacts.ContactID IN
(SELECT contacts_2.ContactID
FROM contacts AS contacts_2
INNER JOIN contacts_link_emails AS contacts_link_emails_2 ON
contacts_2.ContactID = contacts_link_emails_2.ContactID
LEFT OUTER JOIN contacts_def_jobfunctions ON
contacts_2.JobTitle = contacts_def_jobfunctions.JobID
RIGHT OUTER JOIN newsletterremovelist ON
contacts_link_emails_2.Email = newsletterremovelist.EmailAddress
WHERE (contacts_def_jobfunctions.ParentJobID <> 1841)
GROUP BY contacts_2.ContactID
UNION
SELECT contacts_1.ContactID
FROM contacts_link_jobfunctions
INNER JOIN contacts_def_jobfunctions AS contacts_def_jobfunctions_1 ON
contacts_link_jobfunctions.JobID = contacts_def_jobfunctions_1.JobID
AND contacts_def_jobfunctions_1.ParentJobID <> 1841
INNER JOIN contacts AS contacts_1 ON
contacts_link_jobfunctions.ContactID = contacts_1.ContactID
INNER JOIN contacts_link_emails AS contacts_link_emails_1 ON
contacts_link_emails_1.ContactID = contacts_1.ContactID
LEFT OUTER JOIN newsletterremovelist AS newsletterremovelist_1 ON
contacts_link_emails_1.Email = newsletterremovelist_1.EmailAddress
GROUP BY contacts_1.ContactID))
While this query is now super fast (about 3 seconds), I've blown part of the logic somewhere - it only returns 14,863 rows (instead of the 18,215 rows that I believe is accurate).
The results seem near correct. I'm working to discover what data might be missing in the result set.
Can you please coach me through whatever I've done wrong here?
Thanks,
Russell Schutte
The main problem with your original query was that you had two extra joins just to introduce duplicates and then a DISTINCT to get rid of them.
Use this:
SELECT cle.Email,
c.ContactID,
c.First AS ContactFirstName,
c.Last AS ContactLastName,
c.InstitutionID,
izip.CountyID,
izip.StateID,
izip.DistrictID
FROM dbo.contacts c
INNER JOIN
dbo.institutionswithzipcodesadditional izip
ON izip.InstitutionID = c.InstitutionID
INNER JOIN
dbo.contacts_link_emails cle
ON cle.ContactID = c.ContactID
WHERE cle.Email NOT IN
(
SELECT EmailAddress
FROM dbo.newsletterremovelist
)
AND EXISTS
(
SELECT NULL
FROM dbo.contacts_def_jobfunctions cdj
WHERE cdj.JobId = c.JobTitle
AND cdj.ParentJobId <> '1841'
UNION ALL
SELECT NULL
FROM dbo.contacts_link_jobfunctions clj
JOIN dbo.contacts_def_jobfunctions cdj
ON cdj.JobID = clj.JobID
WHERE clj.ContactID = c.ContactID
AND cdj.ParentJobId <> '1841'
)
ORDER BY
email
Create the following indexes:
newsletterremovelist (EmailAddress)
contacts_link_jobfunctions (ContactID, JobID)
contacts_def_jobfunctions (JobID)
Do you get the same results when you do:
SELECT count(*)
FROM
dbo.contacts_def_jobfunctions AS contacts_def_jobfunctions_3
INNER JOIN
dbo.contacts
INNER JOIN
dbo.contacts_link_emails
ON dbo.contacts.ContactID = dbo.contacts_link_emails.ContactID
ON contacts_def_jobfunctions_3.JobID = dbo.contacts.JobTitle
SELECT COUNT(*)
FROM
contacts
INNER JOIN contacts_link_jobfunctions
ON contacts.ContactID = contacts_link_jobfunctions.ContactID
INNER JOIN contacts_link_emails
ON contacts.ContactID = contacts_link_emails.ContactID
If so keep adding each join conditon on until you don't get the same results and you will see where your mistake was. If all the joins are the same, then look at the where clauses. But I will be surprised if it isn't in the first join because the syntax you have orginally won't even work on SQL Server and it is pretty nonstandard SQL and may have been incorrect all along but no one knew.
Alternatively, pick a few of the records that are returned in the orginal but not the revised. Track them through the tables one at a time to see if you can find why the second query filters them out.
I'm not directly sure what is wrong, but when I run in to this situation, the first thing I do is start removing variables.
So, comment out the where clause. How many rows are returned?
If you get back the 11,604 rows then you've isolated the problems to the joins. Work though the joins, commenting each one out (remove the associated columns too) and figure out how many rows are eliminated.
As you do this, aim to find what is causing the desired rows to be eliminated. Once isolated, consider the join differences between the first query and the second query.
In looking at the first query, you could probably just modify that to eliminate any INs and instead do a EXISTS instead.
Consider your indexes as well. Any thing in the where or join clauses should probably be indexed.