Stored procedure sql server 2008 NOT IN - sql

I have created a query which allows me to view all of the items that have been ordered by customers where the company name = Best Baths using the following code.
Select co.OrderID, cu.FName + ' ' + cu.SName as 'Name',
cu.Address1 + ', ' + cu.Address2 + ', ' + cu.Address3 as 'Dispatch Address',
cu.PostCode,
ma.MaterialName as 'Item',
mi.Price as 'Item Price',
co.DateOrdered as 'Order Date',
pm.DateReceived,
CASE WHEN la.Status = 'Blocked' THEN 'Blocked' ELSE 'Active' END AS Status
from Customers cu
-- inner join the following to find customers orders and cost
inner join CustomerOrder co on co.CustomerID = cu.CustomerID
inner join ItemOrder io on co.ID = io.ItemOrderID
inner join materialItem mi on io.MaterialID = mi.MaterialItemID
inner join Material ma on io.MaterialID = ma.MaterialItemID
left join ItemForInvoice ifi on io.ItemOrderID = ifi.ItemOrderID
left join Invoice iv on ifi.InvoiceItemID = iv.InvoiceItemID
left join PaymentMethod pm on iv.InvoiceID = pm.InvoiceID
left join LockedAccount la on pm.PaymentID = la.PaymentID
inner join Suppliers su on mi.SupplierID = su.SuppliersID
inner join SupplierDetails sd on su.SuppliersID = sd.SuppliersID
Where su.SuppliersName = 'Best Baths'
I now want to create a query thats shows items that have not yet been ordered, can anybody point me in the right direction?

It's not obvious from your query as to what tables what, but the basic query would be something like
SELECT items.id, COUNT(orders.itemid) AS cnt
FROM items
LEFT JOIN orders ON items.id = orders.itemid
GROUP BY items.id
HAVING (cnt = 0)

Annoscia, look this example:
(SELECT coll FROM TableA)
EXCEPT
(SELECT coll FROM TableB)
it's mean:
SELECT DISTINCT coll
FROM TableA
WHERE NOT EXISTS (SELECT *
FROM TableB
WHERE TableA.col1 = TableB.col1)
for your case it will be so:
Select co.OrderID, cu.FName + ' ' + cu.SName as 'Name',
cu.Address1 + ', ' + cu.Address2 + ', ' + cu.Address3 as 'Dispatch Address',
cu.PostCode,
ma.MaterialName as 'Item',
mi.Price as 'Item Price',
co.DateOrdered as 'Order Date',
pm.DateReceived,
CASE WHEN la.Status = 'Blocked' THEN 'Blocked' ELSE 'Active' END AS Status
from Customers cu
-- inner join the following to find customers orders and cost
inner join CustomerOrder co on co.CustomerID = cu.CustomerID
inner join ItemOrder io on co.ID = io.ItemOrderID
inner join materialItem mi on io.MaterialID = mi.MaterialItemID
inner join Material ma on io.MaterialID = ma.MaterialItemID
left join ItemForInvoice ifi on io.ItemOrderID = ifi.ItemOrderID
left join Invoice iv on ifi.InvoiceItemID = iv.InvoiceItemID
left join PaymentMethod pm on iv.InvoiceID = pm.InvoiceID
left join LockedAccount la on pm.PaymentID = la.PaymentID
inner join Suppliers su on mi.SupplierID = su.SuppliersID
inner join SupplierDetails sd on su.SuppliersID = sd.SuppliersID
EXCEPT
Select co.OrderID, cu.FName + ' ' + cu.SName as 'Name',
cu.Address1 + ', ' + cu.Address2 + ', ' + cu.Address3 as 'Dispatch Address',
cu.PostCode,
ma.MaterialName as 'Item',
mi.Price as 'Item Price',
co.DateOrdered as 'Order Date',
pm.DateReceived,
CASE WHEN la.Status = 'Blocked' THEN 'Blocked' ELSE 'Active' END AS Status
from Customers cu
-- inner join the following to find customers orders and cost
inner join CustomerOrder co on co.CustomerID = cu.CustomerID
inner join ItemOrder io on co.ID = io.ItemOrderID
inner join materialItem mi on io.MaterialID = mi.MaterialItemID
inner join Material ma on io.MaterialID = ma.MaterialItemID
left join ItemForInvoice ifi on io.ItemOrderID = ifi.ItemOrderID
left join Invoice iv on ifi.InvoiceItemID = iv.InvoiceItemID
left join PaymentMethod pm on iv.InvoiceID = pm.InvoiceID
left join LockedAccount la on pm.PaymentID = la.PaymentID
inner join Suppliers su on mi.SupplierID = su.SuppliersID
inner join SupplierDetails sd on su.SuppliersID = sd.SuppliersID
Where su.SuppliersName = 'Best Baths'

If you're after the materials (i.e. item) that have not yet been ordered, then an NOT EXISTS clause will work well. You only need to check that it has not been involved in an order via ItemOrder table.
Select ma.MaterialName as [Item],
mi.Price as [Item Price]
from Material ma
join materialItem mi on io.MaterialID = mi.MaterialItemID
where not exists (select *
from ItemOrder io
where io.MaterialID = ma.MaterialItemID)
PLEASE do not quote column aliases using (') single quotes in future, use the square brackets.

Related

SQL Server : SUM DISTINCT GROUP BY

I'm currently creating a query to sum the code below
select distinct
opch.docentry as 'AP Invoice #',
pch1.linenum as 'AP Invoice Line #',
pch1.itemcode as 'Item Code',
pch1.dscription as 'Item Name',
pch1.freetxt as 'Free Text',
pch1.priceafvat as 'Gross Price',
pch1.quantity as 'Quantity',
pch1.gtotal as 'Gross Total'
from
opch
inner join
pch1 on opch.docentry = pch1.docentry
inner join
opdn on opdn.docentry = pch1.basedocnum
inner join
pdn1 on opdn.docentry = pdn1.docentry
inner join
opor on opor.docentry = pdn1.basedocnum
inner join
por1 on opor.docentry = por1.docentry
where
pch1.u_budgetno = '57'
and opch.canceled = 'N'
and opdn.docstatus = 'C'
and opdn.canceled = 'N'
and opor.docstatus = 'C'
and opor.canceled = 'N'
order by
opch.docentry
This is the sum statement I've tried
select
opch.docentry,
sum(pch1.gtotal)
from
opch
inner join
pch1 on opch.docentry = pch1.docentry
inner join
opdn on opdn.docentry = pch1.basedocnum
inner join
pdn1 on opdn.docentry = pdn1.docentry
inner join
opor on opor.docentry = pdn1.basedocnum
inner join
por1 on opor.docentry = por1.docentry
where
pch1.u_budgetno = '57'
and opch.canceled = 'N'
and opdn.docstatus = 'C'
and opdn.canceled = 'N'
and opor.docstatus = 'C'
and opor.canceled = 'N'
group by
opch.docentry, opdn.docstatus
It however doesn't return the correct amount as it duplicates some answers based on the connected tables.
Requesting assistance on what I'm doing wrong.
*Update
This is the result from the select distinct query
enter image description here
I'm aiming for the sum query to sum the results from the pch1.gtotal column
Thank you.
The problem is in the join you are doing between the invoice and the delivery note. You are not joining the line so it multiplies the results. The correct join is done using BaseEntry, BaseLine and BaseType. The same applies to the join with the purchase order.
select
opch.docentry,
sum(pch1.gtotal)
from
opch
inner join
pch1 on opch.docentry = pch1.docentry
inner join
pdn1 on pdn1.docentry = pch1.baseentry and pdn1.linenum = pch1.baseline and pdn1.objtype = pch1.basetype
inner join
opdn on opdn.docentry = pdn1.docentry
inner join
por1 on por1.docentry = pdn1.baseentry and por1.linenum = pdn1.baseline and por1.objtype = pdn1.basetype
inner join
opor on opor.docentry = por1.docentry
where
pch1.u_budgetno = '57'
and opch.canceled = 'N'
and opdn.docstatus = 'C'
and opdn.canceled = 'N'
and opor.docstatus = 'C'
and opor.canceled = 'N'
group by
opch.docentry

SQL - charges and payments in same column; how to break it out

I have a SQL query that is pulling data from multiple tables (I have 11 joins)
There is an "ARTransaction" table which contains charges, payments, adjustments, etc. and there is a "transactionCodeID" column inside of that which describes the type of transaction.
I am trying to select a lot of data, but need two separate columns(the ones with comments above them), one for charges and one for payments. Is there a way to achieve this without using the where clause? I tried to use a nested select statement but it returned the same value for every single row (the total amount)
I am attaching the query below - thanks in advance! Also I am fairly new to data retrieval so if anything else looks wonky any other advice is greatly appreciated.
SELECT CONVERT(varchar(10),sl.ServiceDtFrom, 101) AS 'srvdate'
, f.Alias AS 'svc dprtmnt'
, CASE WHEN pc.Alias IS NULL
THEN po.Name
ELSE pc.Description END AS 'svc dept grp'
, COUNT(clm.ID) AS 'clm cnt'
, COUNT(p.ID) AS 'ptnt count'
/* 1 */
, SUM(ar.Amount) AS 'all chgs' --ONLY CHARGES (tt.ID IN(1,2))
, SUM(sl.Units + sl.TimeUnits + sl.PhysicalStatusUnits) AS 'chg units sum'
/* 2 */
, SUM(ar.Amount) AS 'net pmt' --ONLY PAYMENTS (tt.ID IN(3,4,9,10,11,12,20,21))
FROM ARTransaction ar WITH (NOLOCK)
LEFT JOIN ServiceLine sl WITH (NOLOCK)
ON ar.ServiceLineID = sl.ID
LEFT JOIN Incident i WITH (NOLOCK)
ON sl.IncidentID = i.ID
LEFT JOIN HealthCareFacility f WITH (NOLOCK)
ON i.FacilityID = f.ID
LEFT JOIN ProvOrgFacility poc WITH (NOLOCK)
ON poc.FacilityID = f.ID
LEFT JOIN ProfitCenter pc WITH (NOLOCK)
ON poc.ProfitCenterID = pc.ID
LEFT JOIN ProviderOrganization po WITH (NOLOCK)
ON i.ProvOrgID = po.ID
LEFT JOIN Claim clm WITH (NOLOCK)
ON i.ID = clm.IncidentID
LEFT JOIN Person p WITH (NOLOCK)
ON i.PatientID = p.ID
LEFT JOIN TransactionCode tc WITH (NOLOCK)
ON ar.TransactionCodeID = tc.ID
LEFT JOIN TransactionType tt WITH (NOLOCK)
ON tc.TransactionTypeID = tt.ID
WHERE i.IsReversed <> 1
AND sl.ServiceDtFrom IS NOT NULL
GROUP BY
sl.ServiceDtFrom, f.Alias
, po.Name, pc.Alias, pc.Description
ORDER BY 1,3,2
You can use CASE statements to achieve this:-
SELECT CONVERT(varchar(10),sl.ServiceDtFrom, 101) AS 'srvdate'
, f.Alias AS 'svc dprtmnt'
, CASE WHEN pc.Alias IS NULL
THEN po.Name
ELSE pc.Description END AS 'svc dept grp'
, COUNT(clm.ID) AS 'clm cnt'
, COUNT(p.ID) AS 'ptnt count'
/* 1 */
, SUM(case when tt.ID IN(1,2) then ar.Amount else 0 end) AS 'all chgs' --ONLY CHARGES (tt.ID IN(1,2))
, SUM(sl.Units + sl.TimeUnits + sl.PhysicalStatusUnits) AS 'chg units sum'
/* 2 */
, SUM(case when tt.ID IN(3,4,9,10,11,12,20,21) then ar.Amount else 0 end) AS 'net pmt' --ONLY PAYMENTS (tt.ID IN(3,4,9,10,11,12,20,21))
FROM ARTransaction ar WITH (NOLOCK)
LEFT JOIN ServiceLine sl WITH (NOLOCK)
ON ar.ServiceLineID = sl.ID
LEFT JOIN Incident i WITH (NOLOCK)
ON sl.IncidentID = i.ID
LEFT JOIN HealthCareFacility f WITH (NOLOCK)
ON i.FacilityID = f.ID
LEFT JOIN ProvOrgFacility poc WITH (NOLOCK)
ON poc.FacilityID = f.ID
LEFT JOIN ProfitCenter pc WITH (NOLOCK)
ON poc.ProfitCenterID = pc.ID
LEFT JOIN ProviderOrganization po WITH (NOLOCK)
ON i.ProvOrgID = po.ID
LEFT JOIN Claim clm WITH (NOLOCK)
ON i.ID = clm.IncidentID
LEFT JOIN Person p WITH (NOLOCK)
ON i.PatientID = p.ID
LEFT JOIN TransactionCode tc WITH (NOLOCK)
ON ar.TransactionCodeID = tc.ID
LEFT JOIN TransactionType tt WITH (NOLOCK)
ON tc.TransactionTypeID = tt.ID
WHERE i.IsReversed <> 1
AND sl.ServiceDtFrom IS NOT NULL
GROUP BY

getting repeated rows

I am not able to get why i am getting repeated data for below query. Although i have used distinct.
The query is as below- Please help :
Might be some problem with joins
SELECT DISTINCT(UM.USERNAME)'USER_NAME'
,UM.FIRSTNAME + ' ' + UM.LASTNAME AS 'EMPLOYEE NAME'
,US.USER_NAME 'USER_ID'
,US.MS_RIT_REPORTING_GROUP_MST_KEY
,RG.REPORTING_GROUP_NAME
,US.MS_RIT_REGION_MST_KEY
,RM.REGION_NAME
,US.MS_RIT_SUB_REGION_MST_KEY
,SM.SUB_REGION_NAME
,TP.TASK_MST_KEY
,TTM.TASK_TYPE_NAME
,CT.*
,FM.TASK_STATUS
,FM.TASK_START_DATE
,FM.TASK_END_DATE
,SRM.ROLE_NAME AS ROLENAME
FROM USERS_MASTER UM
INNER JOIN MS_RIT_USER_SKILLSET_MAP US ON UM.USERID = US.USER_NAME
INNER JOIN DIM_MS_RIT_REPORTING_GROUP_MST RG ON US.MS_RIT_REPORTING_GROUP_MST_KEY = RG.MS_RIT_REPORTING_GROUP_MST_KEY
AND UPPER(RG.ACTIVE) IN ('YES','1','Y')
INNER JOIN DIM_MS_RIT_REGION_MST RM ON US.MS_RIT_REGION_MST_KEY = RM.MS_RIT_REGION_MST_KEY
AND UPPER(RM.ACTIVE) IN ('YES','1','Y')
INNER JOIN DIM_MS_RIT_SUB_REGION_MST SM ON US.MS_RIT_SUB_REGION_MST_KEY = SM.MS_RIT_SUB_REGION_MST_KEY
AND UPPER(SM.ACTIVE) IN ('YES','1','Y')
INNER JOIN MS_RIT_USER_TASK_MAP TP ON CONVERT(VARCHAR,UM.USERID) = TP.USER_ID
INNER JOIN MS_RIT_CREATE_TASK CT ON CT.TASK_ID = TP.TASK_MST_KEY
INNER JOIN WF_FRM_28_MST FM ON FM.TASK_ID = CT.TASK_ID
INNER JOIN SEC_USER_ROLE SR ON SR.USER_ID = UM.USERNAME
INNER JOIN SEC_ROLE_MST SRM ON SRM.ROLE_CODE = SR.ROLE_CODE
INNER JOIN MS_RIT_TASK_TYPE_MASTER TTM ON CT.TASK_TYPE = TTM.TASK_TYPE_ID
Use UNION to get rid of duplicates
One solution to check if you have duplicates is to do a UNION using the same query, if no rows were removed then they are not duplicates.
(SELECT DISTINCT(UM.USERNAME)'USER_NAME'
,UM.FIRSTNAME + ' ' + UM.LASTNAME AS 'EMPLOYEE NAME'
,US.USER_NAME 'USER_ID'
,US.MS_RIT_REPORTING_GROUP_MST_KEY
,RG.REPORTING_GROUP_NAME
,US.MS_RIT_REGION_MST_KEY
,RM.REGION_NAME
,US.MS_RIT_SUB_REGION_MST_KEY
,SM.SUB_REGION_NAME
,TP.TASK_MST_KEY
,TTM.TASK_TYPE_NAME
,CT.*
,FM.TASK_STATUS
,FM.TASK_START_DATE
,FM.TASK_END_DATE
,SRM.ROLE_NAME AS ROLENAME
FROM USERS_MASTER UM
INNER JOIN MS_RIT_USER_SKILLSET_MAP US ON UM.USERID = US.USER_NAME
INNER JOIN DIM_MS_RIT_REPORTING_GROUP_MST RG ON US.MS_RIT_REPORTING_GROUP_MST_KEY = RG.MS_RIT_REPORTING_GROUP_MST_KEY
AND UPPER(RG.ACTIVE) IN ('YES','1','Y')
INNER JOIN DIM_MS_RIT_REGION_MST RM ON US.MS_RIT_REGION_MST_KEY = RM.MS_RIT_REGION_MST_KEY
AND UPPER(RM.ACTIVE) IN ('YES','1','Y')
INNER JOIN DIM_MS_RIT_SUB_REGION_MST SM ON US.MS_RIT_SUB_REGION_MST_KEY = SM.MS_RIT_SUB_REGION_MST_KEY
AND UPPER(SM.ACTIVE) IN ('YES','1','Y')
INNER JOIN MS_RIT_USER_TASK_MAP TP ON CONVERT(VARCHAR,UM.USERID) = TP.USER_ID
INNER JOIN MS_RIT_CREATE_TASK CT ON CT.TASK_ID = TP.TASK_MST_KEY
INNER JOIN WF_FRM_28_MST FM ON FM.TASK_ID = CT.TASK_ID
INNER JOIN SEC_USER_ROLE SR ON SR.USER_ID = UM.USERNAME
INNER JOIN SEC_ROLE_MST SRM ON SRM.ROLE_CODE = SR.ROLE_CODE
INNER JOIN MS_RIT_TASK_TYPE_MASTER TTM ON CT.TASK_TYPE = TTM.TASK_TYPE_ID)
UNION
(SELECT DISTINCT(UM.USERNAME)'USER_NAME'
,UM.FIRSTNAME + ' ' + UM.LASTNAME AS 'EMPLOYEE NAME'
,US.USER_NAME 'USER_ID'
,US.MS_RIT_REPORTING_GROUP_MST_KEY
,RG.REPORTING_GROUP_NAME
,US.MS_RIT_REGION_MST_KEY
,RM.REGION_NAME
,US.MS_RIT_SUB_REGION_MST_KEY
,SM.SUB_REGION_NAME
,TP.TASK_MST_KEY
,TTM.TASK_TYPE_NAME
,CT.*
,FM.TASK_STATUS
,FM.TASK_START_DATE
,FM.TASK_END_DATE
,SRM.ROLE_NAME AS ROLENAME
FROM USERS_MASTER UM
INNER JOIN MS_RIT_USER_SKILLSET_MAP US ON UM.USERID = US.USER_NAME
INNER JOIN DIM_MS_RIT_REPORTING_GROUP_MST RG ON US.MS_RIT_REPORTING_GROUP_MST_KEY = RG.MS_RIT_REPORTING_GROUP_MST_KEY
AND UPPER(RG.ACTIVE) IN ('YES','1','Y')
INNER JOIN DIM_MS_RIT_REGION_MST RM ON US.MS_RIT_REGION_MST_KEY = RM.MS_RIT_REGION_MST_KEY
AND UPPER(RM.ACTIVE) IN ('YES','1','Y')
INNER JOIN DIM_MS_RIT_SUB_REGION_MST SM ON US.MS_RIT_SUB_REGION_MST_KEY = SM.MS_RIT_SUB_REGION_MST_KEY
AND UPPER(SM.ACTIVE) IN ('YES','1','Y')
INNER JOIN MS_RIT_USER_TASK_MAP TP ON CONVERT(VARCHAR,UM.USERID) = TP.USER_ID
INNER JOIN MS_RIT_CREATE_TASK CT ON CT.TASK_ID = TP.TASK_MST_KEY
INNER JOIN WF_FRM_28_MST FM ON FM.TASK_ID = CT.TASK_ID
INNER JOIN SEC_USER_ROLE SR ON SR.USER_ID = UM.USERNAME
INNER JOIN SEC_ROLE_MST SRM ON SRM.ROLE_CODE = SR.ROLE_CODE
INNER JOIN MS_RIT_TASK_TYPE_MASTER TTM ON CT.TASK_TYPE = TTM.TASK_TYPE_ID)

sql 2008 error 'the column prod_desc1 was specified multiple times for "a"'

I've got this ginormous sql select statement I'm using in a SSRS 2008 report. I need field "prod_desc1" from the Product table, but also the same named field from Order_Line. I've aliased both of them but I'm still getting the error. Here's my statment:
SELECT order_num, quote_num, cust_num, cust_desc, ship_via_desc, whse_desc, slsm_desc, ar_term_desc, vend_desc, pline_desc, major_grp, cust_po_num, ord_date, req_date, shp_date, ord_type, tot_ord_$, pline_num, prod_num, price_ext, STATUS, prod_desc1 as prod_desc, prod_desc1 as com1, prod_desc2 as com2, net_price, seq_num
FROM (SELECT o.order_num, o.quote_num, o.cust_num, c.cust_desc, s.ship_via_desc, w.whse_desc, sa.slsm_desc, t.ar_term_desc, v.vend_desc, ca.pline_desc, ca.major_grp, o.cust_po_num, o.ord_date, o.req_date, o.shp_date, o.ord_type, o.tot_ord_$, ol. pline_num, ol.prod_num, price_ext, 'Open' AS STATUS, p.prod_desc1, ol.prod_desc1, ol.prod_desc2, ol.net_price, seq_num
FROM [ORDER] o
left outer join order_line ol on o.order_num = ol.order_num
left outer join product p on ol.prod_num = p.prod_num
left outer join customer c on o.cust_num = c.cust_no
left outer join ship_via s on o.ship_via_num = s.ship_via_id
left outer join whse_addr w on o.shp_whse = w.whse_num
left outer join salesman sa on o.slsm2_num = sa.slsm_num
left outer join terms t on o.ar_term_num = t.ar_term_num
left outer join vend v on ol.prim_vend_num = v.vend_num
left outer join category ca on ol.pline_Num = ca.pline_Id
WHERE (#OrderNum is null OR o.order_num = (#OrderNum)) and
o.cust_num IN (#CustomerNumber) and
(ol.prim_vend_num IN (#VendNum) or ol.prim_vend_num is NULL) and
o.req_date between (#ReqDateFrom) and (#ReqDateTo) and
o.ord_date between (#EntDateFrom) and (#EntDateTo) and
(c.slsm_num = (#SlsmnRealNum) and ol.major_grp IN ('C', 'R', 'W') or c.slsm2_num = (#SlsmnRealNum) and ol.major_grp IN ('P', 'S')) and
ol.major_grp IN (#MajorGrp) and
ol.pline_num IN (#ProductLine) and
(#PONum is null OR o.cust_po_num LIKE ('%' + #PONum + '%')) and
(#ItemNum is null OR ol.prod_num = (#ItemNum))
UNION ALL
SELECT o.order_num, o.quote_num, o.cust_num, c.cust_desc, s.ship_via_desc, w.whse_desc, sa.slsm_desc, t.ar_term_desc, v.vend_desc, ca.pline_desc, ca.major_grp, o.cust_po_num, o.ord_date, o.req_date, o.shp_date, o.ord_type, o.tot_ord_$, ol.pline_num, ol.prod_num, net_ext, 'Closed' AS STATUS, p.prod_desc1, ol.prod_desc1, ol.prod_desc2, ol.net_price, seq_num
FROM ORDER_HISTORY o
left outer join order_history_line ol on o.order_num = ol.order_num
left outer join product p on ol.prod_num = p.prod_num
left outer join customer c on o.cust_num = c.cust_no
left outer join ship_via s on o.ship_via_num = s.ship_via_id
left outer join whse_addr w on o.shp_whse = w.whse_num
left outer join salesman sa on o.slsm2_num = sa.slsm_num
left outer join terms t on o.ar_term_num = t.ar_term_num
left outer join vend v on ol.prim_vend_num = v.vend_num
left outer join category ca on ol.pline_Num = ca.pline_Id
WHERE (#OrderNum is null OR o.order_num = (#OrderNum)) and
o.cust_num IN (#CustomerNumber) and
(ol.prim_vend_num IN (#VendNum) or ol.prim_vend_num is NULL) and
o.req_date between (#ReqDateFrom) and (#ReqDateTo) and
o.ord_date between (#EntDateFrom) and (#EntDateTo) and
(c.slsm_num = (#SlsmnRealNum) and ol.major_grp IN ('C', 'R', 'W') or c.slsm2_num = (#SlsmnRealNum) and ol.major_grp IN ('P', 'S')) and
ol.major_grp IN (#MajorGrp) and
ol.pline_num IN (#ProductLine) and
(#PONum is null OR o.cust_po_num LIKE ('%' + #PONum + '%')) and
(#ItemNum is null OR ol.prod_num = (#ItemNum))) as a
WHERE (STATUS = CASE WHEN #OrderType = 'Both' THEN STATUS ELSE #OrderType END) ORDER BY cust_desc, req_date, vend_desc
any help would be greatly appreciated! :)

join 2 sql queries and concatenate the results?

I have these 2 queries that almost give me the data I need:
SELECT Products.ItemID, Products.ItemID + '-' + ModifierListItems.ItemID AS SizeItemID
FROM ModifierLists INNER JOIN
ProductModifierLists ON ModifierLists.ModifierListID = ProductModifierLists.ModifierListID INNER JOIN
ModifierListItems ON ModifierLists.ModifierListID = ModifierListItems.ModifierListID INNER JOIN
Products ON ProductModifierLists.ItemID = Products.ItemID AND ProductModifierLists.ManufacturerID = Products.ManufacturerID
WHERE (Products.ManufacturerID = 262) AND ModifierListName='Size'
ORDER BY Products.ItemID
SELECT Products.ItemID, ModifierListItems.ItemID AS ColorItemID
FROM ModifierLists INNER JOIN
ProductModifierLists ON ModifierLists.ModifierListID = ProductModifierLists.ModifierListID INNER JOIN
ModifierListItems ON ModifierLists.ModifierListID = ModifierListItems.ModifierListID INNER JOIN
Products ON ProductModifierLists.ItemID = Products.ItemID AND ProductModifierLists.ManufacturerID = Products.ManufacturerID
WHERE (Products.ManufacturerID = 262) AND ModifierListName='Color'
ORDER BY Products.ItemID
The final output I am looking for is the SizeItemID concatenated with the ColorItemID joined on the ItemID.
Sample results of the 2 queries:
ItemID SizeItemID
------- ----------
A A-S
A A-M
B B-M
B B-L
ItemID ColorItemID
------- -----------
A BLK
A WHT
B BLK
B WHT
B GRN
The results I am looking for would be the following:
FinalItemID
-----------
A-S-BLK
A-S-WHT
A-M-BLK
A-M-WHT
B-M-BLK
B-M-WHT
B-M-GRN
B-L-BLK
B-L-WHT
B-L-GRN
You can take your two queries and join them together on ItemId to construct the final value.
In the following query, I also use aliases on your table names. Many people find meaningful aliases easier to read than long table names:
with tsize as (
SELECT p.ItemID,
p.ItemID + '-' + mli.ItemID AS SizeItemID
FROM ModifierLists ml INNER JOIN
ProductModifierLists pml
ON ml.ModifierListID = pml.ModifierListID INNER JOIN
ModifierListItems mli
ON ml.ModifierListID = mli.ModifierListID INNER JOIN
Products p
ON pml.ItemID = Products.ItemID AND
pml.ManufacturerID = p.ManufacturerID
WHERE (p.ManufacturerID = 262) AND ModifierListName='Size'
),
tcolor as (
SELECT p.ItemID, mli.ItemID AS ColorItemID
FROM ModifierLists moli INNER JOIN
ProductModifierLists pml
ON ml.ModifierListID = pml.ModifierListID INNER JOIN
ModifierListItems mli
ON ml.ModifierListID = mli.ModifierListID INNER JOIN
Products p
ON pml.ItemID = Products.ItemID AND
pml.ManufacturerID = p.ManufacturerID
WHERE (Products.ManufacturerID = 262) AND ModifierListName='Color'
)
select SizeItemID+'-'+ColorItemID
from tsize join tcolor
on tsize.itemid = tcolor.ItemID
Well, the cleanest looking way would be to put each query into it's own view. It also might help you understand what you're doing a little better. So if we took the queries and created views:
CREATE VIEW v_ProductSize
AS
SELECT Products.ItemID, Products.ItemID + '-' + ModifierListItems.ItemID AS SizeItemID
FROM ModifierLists INNER JOIN
ProductModifierLists ON ModifierLists.ModifierListID = ProductModifierLists.ModifierListID INNER JOIN
ModifierListItems ON ModifierLists.ModifierListID = ModifierListItems.ModifierListID INNER JOIN
Products ON ProductModifierLists.ItemID = Products.ItemID AND ProductModifierLists.ManufacturerID = Products.ManufacturerID
WHERE (Products.ManufacturerID = 262) AND ModifierListName='Size'
ORDER BY Products.ItemID
CREATE VIEW v_ProductColor
AS
SELECT Products.ItemID, ModifierListItems.ItemID AS ColorItemID
FROM ModifierLists INNER JOIN
ProductModifierLists ON ModifierLists.ModifierListID = ProductModifierLists.ModifierListID INNER JOIN
ModifierListItems ON ModifierLists.ModifierListID = ModifierListItems.ModifierListID INNER JOIN
Products ON ProductModifierLists.ItemID = Products.ItemID AND ProductModifierLists.ManufacturerID = Products.ManufacturerID
WHERE (Products.ManufacturerID = 262) AND ModifierListName='Color'
ORDER BY Products.ItemID
Then you have two simple views you can use normally, right? So your query would be:
SELECT ps.SizeItemID + '-' + pc.ColorItemID
FROM v_ProductSize ps
JOIN v_ProductColor pc ON ps.ItemID=pc.ItemID
See how that works? You're just doing a normal join like you would any other table. Now, say you don't want to create views, or for some reason don't have permission. You can just skip the view part itself, and use subqueries. You're just replacing the reference to the view, with the query itself in parentheses.
So it would look like this:
SELECT ps.SizeItemID + '-' + pc.ColorItemID
FROM (
SELECT Products.ItemID, Products.ItemID + '-' + ModifierListItems.ItemID AS SizeItemID
FROM ModifierLists INNER JOIN
ProductModifierLists ON ModifierLists.ModifierListID = ProductModifierLists.ModifierListID INNER JOIN
ModifierListItems ON ModifierLists.ModifierListID = ModifierListItems.ModifierListID INNER JOIN
Products ON ProductModifierLists.ItemID = Products.ItemID AND ProductModifierLists.ManufacturerID = Products.ManufacturerID
WHERE (Products.ManufacturerID = 262) AND ModifierListName='Size'
ORDER BY Products.ItemID
) ps
JOIN
( SELECT Products.ItemID, ModifierListItems.ItemID AS ColorItemID
FROM ModifierLists INNER JOIN
ProductModifierLists ON ModifierLists.ModifierListID = ProductModifierLists.ModifierListID INNER JOIN
ModifierListItems ON ModifierLists.ModifierListID = ModifierListItems.ModifierListID INNER JOIN
Products ON ProductModifierLists.ItemID = Products.ItemID AND ProductModifierLists.ManufacturerID = Products.ManufacturerID
WHERE (Products.ManufacturerID = 262) AND ModifierListName='Color'
ORDER BY Products.ItemID
) pc ON ps.itemID=pc.ItemID
Now... all that said, and with my coffee finally kicking in, you can greatly simplify the query into one with a one line modification:
SELECT Products.ItemID, Products.ItemID + '-' + colors.ItemID + '-' + sizes.ItemID AS SizeColorItemID
FROM ModifierLists
INNER JOIN ProductModifierLists ON ModifierLists.ModifierListID = ProductModifierLists.ModifierListID
INNER JOIN ModifierListItems sizes ON ModifierLists.ModifierListID = ModifierListItems.ModifierListID
--Put modifier list name in join clause
AND ModifierListName='Size'
INNER JOIN ModifierListItems colors ON ModifierLists.ModifierListID = ModifierListItems.ModifierListID
--same here, but for color
AND ModifierListName = 'Color'
INNER JOIN Products ON ProductModifierLists.ItemID = Products.ItemID
AND ProductModifierLists.ManufacturerID = Products.ManufacturerID
WHERE (Products.ManufacturerID = 262) --Remove modifierlistitem here so you can use it in the join clauses
ORDER BY Products.ItemID
So since we're really pulling the same information in both original queries, with just a single different condition... we can move the modifierlistitem.name into the join clause, then join to that same table again with a different condition. Then we alias the table based on which condition we used (size, color.) That way you can just refer to the alias and pull the correct item id, and concatenate them all at once.
Try this:
You just need make both the queries as derived tables and join on ItemID
Select a.SizeItemID+'-'+b.ColorItemID as FinalItemID
FROM
(SELECT Products.ItemID, Products.ItemID + '-' + ModifierListItems.ItemID AS SizeItemID
FROM ModifierLists INNER JOIN
ProductModifierLists ON ModifierLists.ModifierListID = ProductModifierLists.ModifierListID INNER JOIN
ModifierListItems ON ModifierLists.ModifierListID = ModifierListItems.ModifierListID INNER JOIN
Products ON ProductModifierLists.ItemID = Products.ItemID AND ProductModifierLists.ManufacturerID = Products.ManufacturerID
WHERE (Products.ManufacturerID = 262) AND ModifierListName='Size'
)a
JOIN
(SELECT Products.ItemID, ModifierListItems.ItemID AS ColorItemID
FROM ModifierLists INNER JOIN
ProductModifierLists ON ModifierLists.ModifierListID = ProductModifierLists.ModifierListID INNER JOIN
ModifierListItems ON ModifierLists.ModifierListID = ModifierListItems.ModifierListID INNER JOIN
Products ON ProductModifierLists.ItemID = Products.ItemID AND ProductModifierLists.ManufacturerID = Products.ManufacturerID
WHERE (Products.ManufacturerID = 262) AND ModifierListName='Color'
)b
on a.ItemID=b.ItemID
ORDER BY a.FinalItemID