Subquery with multiple joins involved - sql

Still trying to get used to writing queries and I've ran into a problem.
Select count(region)
where (regionTable.A=1) in
(
select jxn.id, count(jxn.id) as counts, regionTable.A
from jxn inner join
V on jxn.id = V.id inner join
regionTable on v.regionID = regionTable.regionID
group by jxn.id, regionTable.A
)
The inner query gives an ID number in one column, the amount of times they appear in the table, and then a bit attribute if they are in region A. The outer query works but the error I get is incorrect syntax near the keyword IN. Of the inner query, I would like a number of how many of them are in region A

You must specify table name in query before where
Select count(region)
from table
where (regionTable.A=1) in
And you must choose one of them.
where regionTable.A = 1
or
where regionTable.A in (..)

Your query has several syntax errors. Based on your comments, I think there is no need for a subquery and you want this:
select jxn.id, count(jxn.id) as counts, regionTable.A
from jxn inner join
V on jxn.id = V.id inner join
regionTable on v.regionID = regionTable.regionID
where regionTable.A = 1
group by jxn.id, regionTable.A
which can be further simplified to:
select jxn.id, count(jxn.id) as counts
, 1 as A --- you can even omit this line
from jxn inner join
V on jxn.id = V.id inner join
regionTable on v.regionID = regionTable.regionID
where regionTable.A = 1
group by jxn.id

You are getting the error because of this line:
where (regionTable.A=1)
You cannot specify a condition in a where in clause, it should only be column name

Something like this may be what you want:
SELECT COUNT(*)
FROM
(
select jxn.id, count(jxn.id) as counts, regionTable.A
from
jxn inner join
V on jxn.id = V.id inner join
regionTable on v.regionID = regionTable.regionID
group by jxn.id, regionTable.A
) sq
WHERE sq.a = 1

Related

Why is SQL not letting me access information in inner queries?

I'm writing a query to find solve the following question:
"For those customer – product combinations where the product belongs to one of the product lines that have ‘Ethernet’ in their name, list the name of the customer, name of the product, the sales last year and total sales year to date."
Now, I have four tables that I need to use to solve this: xproduct, xprodline, and xsales, and xcustomer. These are related in the following ways:
And they have the following columns:
Since xcustomer and xproduct are not directly related, I'm using xsales to join them, but I'm having issues accessing the information I get from inner queries. This is the code I have so far, but it throws "ORA-00904: "S"."SALES_YEAR_TO_DATE": invalid identifier":
SELECT xcustomer.cust_name, PL.prod_name, S.sales_last_year, S.sales_year_to_date FROM xcustomer
JOIN(
SELECT xsales.sales_cust_nbr FROM xsales
JOIN (
SELECT xproduct.prod_name, xprodline.prodline_pyear_sales, xprodline.prodline_ytd_sales, xproduct.prod_nbr FROM xproduct
INNER JOIN xprodline
ON xproduct.prod_prodline = xprodline.prodline_nbr
WHERE prod_prodline= 1
) PL
ON xsales.sales_prod_nbr = PL.prod_nbr
)S
ON S.sales_cust_nbr = xcustomer.cust_nbr;
Try this:
SELECT xcustomer.cust_name, PL.prod_name, S.sales_last_year, S.sales_year_to_date FROM xcustomer
JOIN(
SELECT xsales.sales_cust_nbr, xsales.sales_last_year, xsales.sales_year_to_date FROM xsales
JOIN (
SELECT xproduct.prod_name, xprodline.prodline_pyear_sales, xprodline.prodline_ytd_sales, xproduct.prod_nbr FROM xproduct
INNER JOIN xprodline
ON xproduct.prod_prodline = xprodline.prodline_nbr
WHERE prod_prodline= 1
) PL
ON xsales.sales_prod_nbr = PL.prod_nbr
)S
ON S.sales_cust_nbr = xcustomer.cust_nbr;
You were missing selecting the columns you needed.
You are missing one more column (PROD_NAME) in your subquery. Here is the updated query:
SELECT xcustomer.cust_name,
S.prod_name,
S.sales_last_year,
S.sales_year_to_date
FROM xcustomer
JOIN(
SELECT xsales.sales_cust_nbr, xsales.sales_last_year, xsales.sales_year_to_date, pl.prod_name
FROM xsales
JOIN (
SELECT xproduct.prod_name, xprodline.prodline_pyear_sales, xprodline.prodline_ytd_sales, xproduct.prod_nbr
FROM xproduct
INNER JOIN xprodline
ON xproduct.prod_prodline = xprodline.prodline_nbr
WHERE prod_prodline= 1
) PL
ON xsales.sales_prod_nbr = PL.prod_nbr
)S
ON S.sales_cust_nbr = xcustomer.cust_nbr;
Also, I think you can directly join the tables and simplify your query as follows:
SELECT C.cust_name,
PL.prod_name,
S.sales_last_year,
S.sales_year_to_date
FROM xcustomer C
JOIN xsales S
ON C.cust_nbr = S.sales_cust_nbr
JOIN xprodline PL
ON S.sales_prod_nbr = PL.prod_nbr
JOIN xproduct P
ON PL.prodline_nbr = P.prod_prodline
WHERE P.prod_prodline= 1

SQL Multiple inner joins with max() for latest recorded entry

Attempting to build SQL with INNER JOIN's. The INNER JOIN's work ok, now I need to add the MAX() function for limiting the rows to just most recent. Added this INNER JOIN client_diagnosis_record ON SELECT cr.PATID, cr.date_of_diagnosis, cr.most_recent_diagnosis...
Received this SQL code error, need some help, I'm sure it a simple oversight but my eyes are getting dim from looking so long...
Syntax error: [SQLCODE: <-4>:
SQLCODE: <-4>:<A term expected, beginning with one of the following: identifier, constant, aggregate, %ALPHAUP, %EXACT, %MVR, %SQLSTRING, %
[%msg: < The SELECT list of the subquery
SELECT pd.patient_name,
cr.PATID,
cr.date_of_diagnosis,
cr.EPISODE_NUMBER,
ce.diagnosing_clinician_value,
ce.data_entry_user_name,
most_recent_diagnosis
FROM client_diagnosis_record cr
INNER JOIN patient_current_demographics pd ON cr.patid = pd.patid
INNER JOIN client_diagnosis_entry ce ON ce.patid = pd.patid
AND cr.ID = ce.DiagnosisRecord
INNER JOIN client_diagnosis_record ON (SELECT cr.PATID,
cr.date_of_diagnosis,
cr.most_recent_diagnosis
FROM ( SELECT patid,
date_of_diagnosis,
MAX(ID) AS most_recent_diagnosis
FROM client_diagnosis_record) cr
INNER JOIN RADplus_users ru ON ru.staff_member_id = ce.diagnosing_clinician_code
WHERE cr.PATID <> '1'
AND ce.diagnosis_status_value ='Active'
AND (ru.user_description LIKE '%SOA' OR ru.user_description LIKE '%OA')
GROUP BY cr.PATID
I tried to re-format you query and it seems your query syntax is not correct. You may try below query -
SELECT pd.patient_name,
cr.PATID,
cr.date_of_diagnosis,
cr.EPISODE_NUMBER,
ce.diagnosing_clinician_value,
ce.data_entry_user_name,
most_recent_diagnosis
FROM client_diagnosis_record cr
INNER JOIN (SELECT patid,
date_of_diagnosis,
MAX(ID) AS most_recent_diagnosis
FROM client_diagnosis_record
GROUP BY patid,
date_of_diagnosis) cr2 ON cr.PATID = cr2.PATID
AND cr.date_of_diagnosis = cr2.date_of_diagnosis
AND cr.ID = cr2.most_recent_diagnosis
INNER JOIN patient_current_demographics pd ON cr.patid = pd.patid
INNER JOIN client_diagnosis_entry ce ON ce.patid = pd.patid
AND cr.ID = ce.DiagnosisRecord
INNER JOIN RADplus_users ru ON ru.staff_member_id = ce.diagnosing_clinician_code
WHERE cr.PATID <> '1'
AND ce.diagnosis_status_value ='Active'
AND (ru.user_description LIKE '%SOA' OR ru.user_description LIKE '%OA')
GROUP BY cr.PATID

Need to understand multiple joins correctly

I was trying to join 3 tables - CurrentProducts, SalesInvoice and SalesInvoiceDetail. SalesInvoiceDetail contains FK/foreign key to the other two tables and some other columns. The first query is ok but the second is not. My question comes at the end of the code.
Right
select *
from CurrentProducts inner join
(dbo.SalesInvoiceDetail inner join dbo.SalesInvoice
on dbo.SalesInvoiceDetail.InvoiceID = dbo.SalesInvoice.InvoiceID
)
on dbo.SalesInvoiceDetail.ProductID = dbo.CurrentProducts.ProductID
Wrong
select *
from CurrentProducts inner join
(select * from
dbo.SalesInvoiceDetail inner join dbo.SalesInvoice
on dbo.SalesInvoiceDetail.InvoiceID = dbo.SalesInvoice.InvoiceID
)
on dbo.SalesInvoiceDetail.ProductID = dbo.CurrentProducts.ProductID
error - Incorrect syntax near the keyword 'on'.
Why is the second query wrong ? Isn't it conceptually the same as the first one ? That is inside join makes a result set. We select * the result set and then join this result set to CurrentProducts ?
The first query is a "plain" join expressed with an older syntax. It can be rewritten as:
select
*
from
CurrentProducts
inner join dbo.SalesInvoiceDetail
on dbo.SalesInvoiceDetail.ProductID = dbo.CurrentProducts.ProductID
inner join dbo.SalesInvoice
on dbo.SalesInvoiceDetail.InvoiceID = dbo.SalesInvoice.InvoiceID
The second query is a join where the second table is a subquery. When you join on a subquery, you must assign an alias to it and use that alias to refer to the columns returned by the subquery:
select
*
from
CurrentProducts
inner join (select *
from dbo.SalesInvoiceDetail
inner join dbo.SalesInvoice
on SalesInvoiceDetail.InvoiceID = SalesInvoice.InvoiceID
) as foo on foo.ProductID = dbo.CurrentProducts.ProductID
You need to alias the inner query. Also, in the first one the parentheses are not needed.
select *
from CurrentProducts inner join
(select * from
dbo.SalesInvoiceDetail inner join dbo.SalesInvoice
on dbo.SalesInvoiceDetail.InvoiceID = dbo.SalesInvoice.InvoiceID
) A
on A.ProductID = dbo.CurrentProducts.ProductID

How to write this SQL statement correctly?

As written in the title: How to write this SQL statement correctly?
select
sl.switch_ip,
sl.switch_name,
count(m.switch_ip) as macentries,
(select arpentries from (select sl1.switch_ip, sl1.switch_name, count(ar.switch_ip) as arpentries
from my_switchlist sl1
left Join my_arptable ar on ar.switch_ip = sl1.switch_ip
group by sl1.switch_ip,sl1.switch_name
order by sl1.switch_ip))
from my_switchlist sl
left Join my_mactable m on m.switch_ip = sl.switch_ip
group by sl.switch_ip,sl.switch_name
order by sl.switch_ip
The select and the sub-select work fine if they are executed separately.
But as soon as I put them together I get the following error:
Error: A subquery has returned not exactly one row.
SQLState: 21000
ErrorCode: -284
Position: 470
Looks like you want both the 'count' aggregates, which should be possible with something like this:
select
macquery.switch_ip,
macquery.switch_name,
macquery.macentries,
arpquery.arpentries
from
(
select
sl.switch_ip as switch_ip,
sl.switch_name as switch_name,
count(m.switch_ip) as macentries
from my_switchlist sl
left outer join my_mactable m
on m.switch_ip = sl.switch_ip
group by
sl.switch_ip,
sl.switch_name
) macquery
join
(
select
sl1.switch_ip as switch_ip,
sl1.switch_name as switch_name,
count(ar.switch_ip) as arpentries
from my_switchlist sl1
left outer join my_arptable ar
on ar.switch_ip = sl1.switch_ip
group by
sl1.switch_ip,
sl1.switch_name
) arpquery
on (macquery.switch_ip = arpquery.switch_ip
and macquery.switch_name = arpquery.switch_name)
Probably there are more than one "sl1.switch_ip,sl1.switch_name" groups in your "my_switchlist, my_arptable" join.
select arpentries from (select sl1.switch_ip, sl1.switch_name, count(ar.switch_ip) as arpentries
from my_switchlist sl1
left Join my_arptable ar on ar.switch_ip = sl1.switch_ip
group by sl1.switch_ip,sl1.switch_name
order by sl1.switch_ip)
The above query should not return more than one result in order you to use its result in your outer query. So probably there is more than one "sl1.switch_ip,sl1.switch_name" group.

What could create a syntax error if you take a SQL query and perform an UNION with itself?

I have this strange error in SQL Server 2005 where I take a working query, add the UNION keyword below it and then copy the query again. In my opinion, this should always be working, but it is not. I get the message 'Incorrect syntax near the keyword 'union'.
What could create this problem ?
To be more specific, here is the complete query :
select distinct deliveries.id, orders.id, 20 + sum(orders.mass1) as allowed_duration
from features_resources
inner join features on features.id = featureid
inner join orders on orders.id = features_resources.resourceid
inner join orderinformations on orders.id = orderinformations.orderid
inner join deliveries on orderinformations.deliveryid = deliveries.id
where features.name = 'O_FRAIS'
and (deliveries.ID IN
(SELECT ID
FROM dbo.DeliveriesInExportedSchedule))
group by deliveries.id, features.name ,orders.id order by deliveries.id
union
select distinct deliveries.id, orders.id, 20 + sum(orders.mass1) as allowed_duration
from features_resources
inner join features on features.id = featureid
inner join orders on orders.id = features_resources.resourceid
inner join orderinformations on orders.id = orderinformations.orderid
inner join deliveries on orderinformations.deliveryid = deliveries.id
where features.name = 'O_FRAIS'
and (deliveries.ID IN
(SELECT ID
FROM dbo.DeliveriesInExportedSchedule))
group by deliveries.id, features.name ,orders.id order by deliveries.id
I have tried to reproduce the error on a smaller query, by starting from a simple query and adding features one by one (inner join, nested queryes, group by, sum,....) but failed to reproduce the error again.
Any idea ?
It is actually the order by deliveries.id in the top half that causes the problem.
The order by needs to apply to the whole query.
Example Syntax
SELECT v1.number
FROM master.dbo.spt_values v1
WHERE v1.number > 2000
UNION
SELECT v2.number
FROM master.dbo.spt_values v2
WHERE v2.number < 10
ORDER BY v1.number
Try putting the individual SELECTs in parentheses:
(SELECT ... )
UNION
(SELECT ... )
The way you have it now, the second WHERE and GROUP BY clauses are ambiguous - should that apply to the SELECT, or to the UNION? I don't have any way to tell, and neither has your DB server.