How to fix SQL query to Left Join a subquery with Where clause? - sql

I'm new to SQL and I'm not certain why I am getting this error. I am trying to left join a sub-query to another query in sql developer.
This is the first query,
SELECT DISTINCT
tl.species,
ag.age
FROM
age_list ag,
tree_list tl
WHERE
ag.tree_id = tl.tree_id
And then the sub-query I would like to left join where the tree_id = tree_number is,
SELECT DISTINCT
sl.tree_spon,
sl.tree_number
FROM spon_list sl
WHERE
sl.tree_spon < 10
When trying to do this I've tried to use,
SELECT DISTINCT
tl.species,
ag.age,
q1.tree_spon
FROM
age_list ag,
tree_list tl
LEFT OUTER JOIN (SELECT DISTINCT
sl.tree_spon,
sl.tree_number
FROM spon_list sl
WHERE sl.tree_spon < 10) q1 on q1.tree_number = tree_list.tree_id
WHERE
ag.tree_id = tl.tree_id
Whatever I change in terms of the alias' for the columns and tables I always get the error, "ORA-00904: invalid identifier error", and that "tree_list.tree_id is invalid identifier", though separately the queries run fine.
Can anyone help, is it an issue with both queries joining on the tl.tree_id?

You can use the ANSI join syntax throughout (rather than mixing in legacy comma joins), joining on ag.tree_id = sl.tree_number (or tl.tree_id = sl.tree_number but they're both equal given the previous join) and putting the filter on sl.tree_spon < 10 into the ON clause as well:
SELECT DISTINCT
tl.species,
ag.age,
sl.tree_spon,
sl.tree_number
FROM age_list ag
INNER JOIN tree_list tl
ON (ag.tree_id = tl.tree_id)
LEFT OUTER JOIN spon_list sl
ON (ag.tree_id = sl.tree_number AND sl.tree_spon < 10)

Change tree_list.tree_id to tl.tree_id

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.

How to do operations between a column and a subquery

I would like to know how I can do operations between a column and a subquery, what I want to do is add to the field Subtotal what was obtained in the subquery Impuestos, the following is the query that I am using for this case.
Select
RC.PURCHID;
LRC.VALUEMST as 'Subtotal',
isnull((
select sum((CONVERT(float, TD1.taxvalue)/100)*LRC1.VALUEMST ) as a
FROM TAXONITEM TOI1
inner join TAXDATA TD1 ON (TD1.TAXCODE = TOI1.TAXCODE and RC.DATAAREAID = TD1.DATAAREAID)
inner join TRANS LRC1 on (LRC1.VEND = RC.RECID)
WHERE TOI1.TAXITEMGROUP = PL.TAXITEMGROUP and RC.DATAAREAID = TOI1.DATAAREAID
), 0) Impuestos
from VEND RC
inner join VENDTABLE VTB on VTB.ACCOUNTNUM = RC.INVOICEACCOUNT
inner join TRANS LRC on (LRC.VEND = RC.RECID)
inner join PURCHLINE PL on (PL.LINENUMBER =LRC.LINENUM and PL.PURCHID =RC.PURCHID)
where year (RC.DELIVERYDATE) =2021 and RC.PURCHASETYPE =3 order by RC.PURCHID;
Hope someone can give me some guidance when doing operations with subqueries.
A few disjointed facts that may help:
When a SELECT statement returns only one row with one column, you can enclose that statement in parenthesis and use it as a plain value. In your case, let's say that select sum(......= TOI1.DATAAREAID returns 500. Then, your outer select's second column is equivalent to isnull(500,0)
You mention in your question "subquery Impuestos". Keep in mind that, although you indeed used a subquery as we mentioned earlier, by the time it was enclosed in parentheses it is not treated as a subquery (more accurately: derived table), but as a value. Thus, the "Impuestos" is only a column alias at this point
I dislike and avoid subqueries before the from, makes things much harder to read. Here is a solution with apply which will keep your code mostly intact:
Select
RC.PURCHID,
LRC.VALUEMST as 'Subtotal',
isnull(subquery1.a, 0) as Impuestos
from VEND RC
inner join VENDTABLE VTB on VTB.ACCOUNTNUM = RC.INVOICEACCOUNT
inner join TRANS LRC on (LRC.VEND = RC.RECID)
inner join PURCHLINE PL on (PL.LINENUMBER =LRC.LINENUM and PL.PURCHID =RC.PURCHID)
outer apply
(
select sum((CONVERT(float, TD1.taxvalue)/100)*LRC1.VALUEMST ) as a
FROM TAXONITEM TOI1
inner join TAXDATA TD1 ON (TD1.TAXCODE = TOI1.TAXCODE and RC.DATAAREAID = TD1.DATAAREAID)
inner join TRANS LRC1 on (LRC1.VEND = RC.RECID)
WHERE TOI1.TAXITEMGROUP = PL.TAXITEMGROUP and RC.DATAAREAID = TOI1.DATAAREAID
) as subquery1
where year (RC.DELIVERYDATE) =2021 and RC.PURCHASETYPE =3 order by RC.PURCHID;

Joining a Query and sub-query

I'm trying to join a query and a sub-query in Access but haven't the faintest idea on how to do that. Rather than saving the sub-query as a different query and then joining it to the main query.
Main query (with reference to sub-query):
SELECT tb200_IraDataIn.tb200_niarnum, tb206_IraAccount.tb206_IraAccDesc,
tb206_IraAccount.tb206_IraAccNum, tb15_Securities.tb15_IsActiveRegister,
tb15_Securities.tb15_NiarDesc, tb15_Securities.tb15_ManpikID, tb200_IraDataIn.tb200_Shovi, tb10_Afik.tb10_InvestTool,
tb206_IraAccount.tb206_IsActive, tb200_IraDataIn.tb200_Shovi,
tb200_IraDataIn.tb200_Shovi/SubQuery1.SumOftb200_Shovi AS Expr1
FROM SubQuery1
INNER JOIN (tb10_Afik
INNER JOIN (tb15_Securities
INNER JOIN (tb206_IraAccount
INNER JOIN tb200_IraDataIn
ON tb206_IraAccount.tb206_IraAccNum = tb200_IraDataIn.tb200_accountNumber)
ON tb15_Securities.tb15_NiarID = tb200_IraDataIn.tb200_niarnum)
ON (tb10_Afik.tb10_AfikID = tb200_IraDataIn.tb200_afik) AND (tb10_Afik.tb10_Erp =tb200_IraDataIn.tb200_ERP))
ON SubQuery1.tb206_IraAccNum = tb206_IraAccount.tb206_IraAccNum
WHERE (((tb15_Securities.tb15_IsActiveRegister)=Yes) AND ((tb10_Afik.tb10_InvestTool)=1
Or (tb10_Afik.tb10_InvestTool)=4 Or (tb10_Afik.tb10_InvestTool)=21 Or
(tb10_Afik.tb10_InvestTool)=3) AND ((tb206_IraAccount.tb206_IsActive)=Yes) AND
(([tb200_IraDataIn].[tb200_Shovi]/[SubQuery1].[SumOftb200_Shovi])>0.1));
subquery (saved as SubQuery1):
SELECT tb206_IraAccount.tb206_IraAccDesc, tb206_IraAccount.tb206_IraAccNum, Sum(tb200_IraDataIn.tb200_Shovi) AS SumOftb200_Shovi
FROM tb206_IraAccount
INNER JOIN tb200_IraDataIn ON tb206_IraAccount.tb206_IraAccNum = tb200_IraDataIn.tb200_accountNumber
WHERE (((tb206_IraAccount.tb206_IsActive)=Yes))
GROUP BY tb206_IraAccount.tb206_IraAccDesc, tb206_IraAccount.tb206_IraAccNum;
How can I put the sql statement of the sub-query inside the same Sql statement of the main query, unlike now?
Thanks!
Nest between parentheses. Nothing else in the main query changes.
SELECT
...
FROM (SELECT tb206_IraAccount.tb206_IraAccDesc, tb206_IraAccount.tb206_IraAccNum, Sum(tb200_IraDataIn.tb200_Shovi) AS SumOftb200_Shovi
FROM tb206_IraAccount
INNER JOIN tb200_IraDataIn ON tb206_IraAccount.tb206_IraAccNum = tb200_IraDataIn.tb200_accountNumber
WHERE (((tb206_IraAccount.tb206_IsActive)=Yes))
GROUP BY tb206_IraAccount.tb206_IraAccDesc, tb206_IraAccount.tb206_IraAccNum) AS SubQuery1
...

Query to return SINGLE DISTINCT row

I have the query below working, the thing is I need to only list each unique "VolumeSerialNumber0" once. There's no shortage of questions and approaches to this problem on SO but they suggest using subqueries and group by clause, but when I try to do that I get an error "columnname is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
I feel like it has to be close I'm just not getting the magical syntax perfectly correct.
SELECT
dbo.v_R_System.Netbios_Name0,
dbo.v_GS_LOGICAL_DISK.TimeStamp,
dbo.v_GS_LOGICAL_DISK.Description0,
dbo.v_GS_LOGICAL_DISK.DeviceID0,
dbo.v_GS_LOGICAL_DISK.DriveType0,
dbo.v_GS_LOGICAL_DISK.Name0,
dbo.v_GS_LOGICAL_DISK.SystemName0,
dbo.v_GS_LOGICAL_DISK.VolumeName0,
dbo.v_GS_LOGICAL_DISK.VolumeSerialNumber0,
dbo.v_GS_PARTITION.Size0,
dbo.v_GS_LOGICAL_DISK.FileSystem0
FROM
dbo.v_R_System
INNER JOIN dbo.v_GS_LOGICAL_DISK
ON dbo.v_R_System.ResourceID = dbo.v_GS_LOGICAL_DISK.ResourceID
INNER JOIN dbo.v_GS_PARTITION
ON dbo.v_GS_LOGICAL_DISK.ResourceID = dbo.v_GS_PARTITION.ResourceID
SELECT
MAX(S.Netbios_Name0),
MAX(L.TimeStamp),
MAX(L.Description0),
MAX(L.DeviceID0),
MAX(L.DriveType0),
MAX(L.Name0),
MAX(L.SystemName0),
MAX(L.VolumeName0),
L.VolumeSerialNumber0,
MAX(P.Size0),
MAX(L.FileSystem0)
FROM
dbo.v_R_System S
INNER JOIN dbo.v_GS_LOGICAL_DISK L
ON S.ResourceID = L.ResourceID
INNER JOIN dbo.v_GS_PARTITION P
ON L.ResourceID = P.ResourceID
GROUP BY
L.VolumeSerialNumber0

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