SQL Join only if all records have a match - sql

I have 3 tables:
CP_carthead (idOrder)
CP_cartrows (idOrder, idCartRow)
CP_shipping (idCartRow, idShipping, dateShipped)
There can be multiple idCartRows per idOrder.
I want to get all orders where all its idCartRows exist in CP_shipping. This seems like it should be simple, but I haven't found much on the web.
Here's my query now:
SELECT
s.idOrder
, s.LatestDateShipped
FROM
CP_carthead o
LEFT OUTER JOIN (
SELECT
MAX(s.dateShipped) [LatestDateShipped]
, r.idOrder
FROM
CP_shipping s
LEFT OUTER JOIN CP_cartrows r ON s.idCartRow = r.idCartRow
GROUP BY
r.idOrder
) s ON o.idOrder = s.idOrder

Your query is returning rows from "s" and not the orders. Based on your question, I came up with this query:
select o.*
from CP_Carthead o
where o.orderId in (select cr.idOrder
from cp_cartrows cr left outer join
cp_shipping s
on cr.idCartRow = s.IdCartrow
group by cr.idOrder
having count(s.idCartRow) = COUNT(*)
)
The subquery in the in statement is getting orders all of whose cartrows are in shipping.

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

Access: Integrating Subquery into excisting Query

The "Last" function in the query below (line 4 & 5)that I'm using is not exactly what I'm after. The last function finds the last record in that table.
What i need find is the most recent record in the table according to a date field.
SELECT
tblinmate.statusid,
tblinmate.activedate,
Last(tblclassificationhistory.classificationid) AS LastOfclassificationID,
Last(tblsquadhistory.squadid) AS LastOfsquadID,
tblperson.firstname,
tblperson.middlename,
tblperson.lastname,
tblinmate.prisonnumber,
tblinmate.droppeddate,
tblinmate.personid,
tblinmate.inmateid
FROM tblsquad
INNER JOIN (tblperson
INNER JOIN ((tblinmate
INNER JOIN (tblclassification
INNER JOIN tblclassificationhistory
ON tblclassification.classificationid =
tblclassificationhistory.classificationid)
ON tblinmate.inmateid =
tblclassificationhistory.inmateid)
INNER JOIN tblsquadhistory
ON tblinmate.inmateid =
tblsquadhistory.inmateid)
ON tblperson.personid = tblinmate.personid)
ON tblsquad.squadid = tblsquadhistory.squadid
GROUP BY tblinmate.statusid,
tblinmate.activedate,
tblperson.firstname,
tblperson.middlename,
tblperson.lastname,
tblinmate.prisonnumber,
tblinmate.droppeddate,
tblinmate.personid,
tblinmate.inmateid;
This query below does just that, finds the most recent record in a table according to a date field.
my problem is i dont know how to integrate this Query into the above to replace the "Last" function
SELECT a.inmateID,
a.classificationID,
b.max_date
FROM (
SELECT tblClassificationHistory.inmateID,
tblClassificationHistory.classificationID,
tblClassificationHistory.reclassificationDate
FROM tblinmate
INNER JOIN tblClassificationHistory
ON tblinmate.inmateID = tblClassificationHistory.inmateID
) a
INNER JOIN (
SELECT tblClassificationHistory.inmateID,
MAX(tblClassificationHistory.reclassificationDate) as max_date
FROM tblinmate
INNER JOIN tblClassificationHistory
ON tblinmate.inmateID = tblClassificationHistory.inmateID
GROUP BY tblClassificationHistory.inmateID
) b
ON a.inmateID = b.inmateID
AND a.reclassificationDate = b.max_date
ORDER BY a.inmateID;
I got a tip from another forum to combine queries like this
SELECT qryMainTemp.*, qrySquad.*, qryClassification.*
FROM (qryMainTemp INNER JOIN qrySquad ON qryMainTemp.inmateID = qrySquad.inmateID) INNER JOIN qryClassification ON qryMainTemp.inmateID = qryClassification.inmateID;
and it worked :) i separated the first query into the two queries it was made of and then combined the three like shown above.
Sadly this made another problem arise the query is now not up-datable..working on a solution for this

Subquery with multiple joins involved

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

How can I get all the rows from master table and relevent row from the detail table in MS-SQL?

I am using MS-SQL and I am trying to write a query which fetches rows from the master table and related rows from the detail table. Now, the thing I want is that it must only fetch the first row from the master table and related field from the detail tables should be blank in that first row, now if there are related rows found in the detail tables, they must be shown in the separate rows. I have been trying using the following query but it is not giving the desired result.
SELECT
DISTINCT
ProductMaster.ProductMasterID, ProductMaster.ProductName,
ProductMaster.SubCategoryID, SubCategory.SubCategoryName,
ProductBrandAndType.ProductBranAndTypeID, ProductBrandAndType.ProductType,
ProductBrandAndType.Brand, ProductMaster.ProductDesc,
ProductMaster.ReOrderLevel
FROM
ProductBrandAndType
RIGHT OUTER JOIN
Inward
ON ProductBrandAndType.ProductBranAndTypeID = Inward.ProductBrandAndTypeID
RIGHT OUTER JOIN
ProductMaster
ON Inward.ProductID = ProductMaster.ProductMasterID
LEFT OUTER JOIN
SubCategory
ON ProductMaster.SubCategoryID = SubCategory.SubCategoryID
ORDER BY
ProductMaster.ProductName,
ProductBrandAndType.ProductType,
ProductBrandAndType.Brand;
Can anyone help me on this?
Regards
Sikandar
Following query worked.
SELECT dbo.ProductMaster.ProductMasterID, dbo.ProductMaster.ProductName, dbo.ProductMaster.SubCategoryID, dbo.ProductMaster.ProductDesc,
dbo.ProductMaster.ReOrderLevel, null as ProductBrandAndTypeID,
null AS Type, null as Brand
FROM dbo.ProductBrandAndType RIGHT OUTER JOIN
dbo.Inward ON dbo.ProductBrandAndType.ProductBranAndTypeID = dbo.Inward.ProductBrandAndTypeID RIGHT OUTER JOIN
dbo.ProductMaster ON dbo.Inward.ProductID = dbo.ProductMaster.ProductMasterID LEFT OUTER JOIN
dbo.SubCategory ON dbo.ProductMaster.SubCategoryID = dbo.SubCategory.SubCategoryID
UNION
SELECT dbo.ProductMaster.ProductMasterID, dbo.ProductMaster.ProductName, dbo.ProductMaster.SubCategoryID, dbo.ProductMaster.ProductDesc,
dbo.ProductMaster.ReOrderLevel, dbo.ProductBrandAndType.ProductBranAndTypeID,
dbo.ProductBrandAndType.ProductType, dbo.ProductBrandAndType.Brand
FROM dbo.ProductBrandAndType RIGHT OUTER JOIN
dbo.Inward ON dbo.ProductBrandAndType.ProductBranAndTypeID = dbo.Inward.ProductBrandAndTypeID RIGHT OUTER JOIN
dbo.ProductMaster ON dbo.Inward.ProductID = dbo.ProductMaster.ProductMasterID LEFT OUTER JOIN
dbo.SubCategory ON dbo.ProductMaster.SubCategoryID = dbo.SubCategory.SubCategoryID
ORDER BY ProductName;
If you just what the first row from the ProductMaster. Then you can do something like this:
;WITH CTE
(
SELECT
ROW_NUMBER() OVER(ORDER BY ProductMaster.ProductMasterID) AS RowNbr,
ProductMaster.ProductName,
ProductMaster.SubCategoryID,
ProductMaster.ProductDesc,
ProductMaster.ReOrderLevel
FROM
ProductMaster
)
SELECT
ProductMaster.ProductMasterID,
ProductMaster.ProductName,
ProductMaster.SubCategoryID,
SubCategory.SubCategoryName,
ProductBrandAndType.ProductBranAndTypeID,
ProductBrandAndType.ProductType,
ProductBrandAndType.Brand,
ProductMaster.ProductDesc,
ProductMaster.ReOrderLevel
FROM
ProductBrandAndType
RIGHT OUTER JOIN Inward
ON ProductBrandAndType.ProductBranAndTypeID = Inward.ProductBrandAndTypeID
RIGHT OUTER JOIN CTE AS ProductMaster
ON Inward.ProductID = ProductMaster.ProductMasterID
AND RowNbr=1
LEFT OUTER JOIN SubCategory
ON ProductMaster.SubCategoryID = SubCategory.SubCategoryID
ORDER BY
ProductMaster.ProductName,
ProductBrandAndType.ProductType,
ProductBrandAndType.Brand;

Max date in view on left outer join

Thanks to a previous question, I found out how to pull the most recent data based on a linked table. BUT, now I have a related question.
The solution that I found used row_number() and PARTITION to pull the most recent set of data. But what if there's a possibility for zero or more rows in a linked table in the view? For example, the table FollowUpDate might have 0 rows, or 1, or more. I just want the most recent FollowUpDate:
SELECT
EFD.FormId
,EFD.StatusName
,MAX(EFD.ActionDate)
,EFT.Name AS FormType
,ECOA.Account AS ChargeOffAccount
,ERC.Name AS ReasonCode
,EAC.Description AS ApprovalCode
,MAX(EFU.FollowUpDate) AS FollowUpDate
FROM (
SELECT EF.FormId, EFD.ActionDate, EFS.Name AS StatusName, EF.FormTypeId, EF.ChargeOffId, EF.ReasonCodeId, EF.ApprovalCodeId,
row_number() OVER ( PARTITION BY EF.FormId ORDER BY EFD.ActionDate DESC ) DateSortKey
FROM Extension.FormDate EFD INNER JOIN Extension.Form EF ON EFD.FormId = EF.FormId INNER JOIN Extension.FormStatus EFS ON EFD.StatusId = EFS.StatusId
) EFD
INNER JOIN Extension.FormType EFT ON EFD.FormTypeId = EFT.FormTypeId
LEFT OUTER JOIN Extension.ChargeOffAccount ECOA ON EFD.ChargeOffId = ECOA.ChargeOffId
LEFT OUTER JOIN Extension.ReasonCode ERC ON EFD.ReasonCodeId = ERC.ReasonCodeId
LEFT OUTER JOIN Extension.ApprovalCode EAC ON EFD.ApprovalCodeId = EAC.ApprovalCodeId
LEFT OUTER JOIN (Select EFU.FormId, EFU.FollowUpDate, row_number() OVER (PARTITION BY EFU.FormId ORDER BY EFU.FollowUpDate DESC) FUDateSortKey FROM Extension.FormFollowUp EFU INNER JOIN Extension.Form EF ON EFU.FormId = EF.FormId) EFU ON EFD.FormId = EFU.FormId
WHERE EFD.DateSortKey = 1
GROUP BY
EFD.FormId, EFD.ActionDate, EFD.StatusName, EFT.Name, ECOA.Account, ERC.Name, EAC.Description, EFU.FollowUpDate
ORDER BY
EFD.FormId
If I do a similar pull using row_number() and PARTITION, I get the data only if there is at least one row in FollowUpDate. Kinda defeats the purpose of a LEFT OUTER JOIN. Can anyone help me get this working?
I rewrote your query - you had unnecessary subselects, and used row_number() for the FUDateSortKey but didn't use the column:
SELECT t.formid,
t.statusname,
MAX(t.actiondate) 'actiondate',
t.formtype,
t.chargeoffaccount,
t.reasoncode,
t.approvalcode,
MAX(t.followupdate) 'followupdate'
FROM (
SELECT t.formid,
fs.name 'StatusName',
t.actiondate,
ft.name 'formtype',
coa.account 'ChargeOffAccount',
rc.name 'ReasonCode',
ac.description 'ApprovalCode',
ffu.followupdate,
row_number() OVER (PARTITION BY ef.formid ORDER BY t.actiondate DESC) 'DateSortKey'
FROM EXTENSION.FORMDATE t
JOIN EXTENSION.FORM ef ON ef.formid = t.formid
JOIN EXTENSION.FORMSTATUS fs ON fs.statusid = t.statusid
JOIN EXTENSION.FORMTYPE ft ON ft.formtypeid = ef.formtypeid
LEFT JOIN EXTENSION.CHARGEOFFACCOUNT coa ON coa.chargeoffid = ef.chargeoffid
LEFT JOIN EXTENSION.REASONCODE rc ON rc.reasoncodeid = ef.reasoncodeid
LEFT JOIN EXTENSION.APPROVALCODE ac ON ac.approvalcodeid = ef.approvalcodeid
LEFT JOIN EXTENSION.FORMFOLLOWUP ffu ON ffu.formid = t.formid) t
WHERE t.datesortkey = 1
GROUP BY t.formid, t.statusname, t.formtype, t.chargeoffaccount, t.reasoncode, t.approvalcode
ORDER BY t.formid
The change I made to allow for FollowUpDate was to use a LEFT JOIN onto the FORMFOLLOWUP table - you were doing an INNER JOIN, so you'd only get rows with FORMFOLLOWUP records associated.
It's pretty hard to guess what's going on without table definitions and sample data.
Also, this is confusing: "the table FollowUpDate might have 0 rows" and you "want the most recent FollowUpDate." (especially when there is no table named FollowUpDate) There is no "most recent FollowUpDate" if there are zero FollowUpDates.
Maybe you want
WHERE <follow up date row number> in (1,NULL)
I figured it out. And as usual, I need a nap. I just needed to change my subselect to something I would swear I'd tried with no success:
SELECT field1, field2
FROM Table1 t1
LEFT JOIN (
SELECT field3, max(dateColumn)
FROM Table2
GROUP BY
field3
) t2
ON (t1.field1 = t2.field3)