This SQL query is taking too long - sql

This SQL query is taking too long
SELECT
s.State
, ServiceCenter
, s.LocationId
, LMG.dbo.ProperCase(LastName + ', ' + FirstName + ' (' + convert(varchar,s.ClientId) + ')') as Client
, ISNULL(ul.ContractorName, ServiceCenter) as ContractorName
, InvoiceId as InvoiceNumber
, s.ItemDescription
, s.Quantity
--, s.Revenue
--, SUM(s.Quantity) as Quantity
, SUM(s.Quantity * s.UnitPrice) as Revenue
--, SUM(s.Quantity * s.Revenue) as Total
, SUM(Quantity * lxref.Amount) as ContractorPayment
, (SELECT InvoiceAmount FROM AG1.MAMOZI.dbo.tInvoices i WHERE s.InvoiceId = i.invoiceId AND DeletedStatus IS NULL) as InvoiceAmount
, (SELECT SUM(Payment) FROM AG1.MAMOZI.dbo.tPayments p WHERE s.InvoiceId = p.invoiceId AND DeletedStatus IS NULL) as PaymentAmount
, (SELECT PaymentType FROM #PaymentTypeGuardian pt WHERE pt.ClientId = s.ClientId AND pt.InvoiceId = s.InvoiceId) as PaymentType
, ISNULL((SELECT SUM(AccountBalance) FROM [PLUSREPORT].Warehouse_LMG1.dbo.RptAccountBalance a WHERE a.CompanyId = 3 AND a.ClientId = CAST(s.ClientId as varchar(max))), 0) as AccountBalance
FROM #ServicePaymentGuardian s
INNER JOIN AG1.MAMOZI.dbo.tClient c on s.ClientId = c.ClientId
INNER JOIN DATABASESAVE.MAMO.org.LocationExtended le on s.LocationID = le.OrgDatabaseid
INNER JOIN DATABASESAVE.MAMO.jur.Location ul on le.LocationId = ul.LocationId AND ul.LocationTypeid = 2
INNER JOIN DATABASESAVE.MAMO.base.Jurisdiction uj on ul.JurisdictionId = uj.JurisdictionId AND uj.CompanyId = 3
INNER JOIN DATABASESAVE.MAMO.jur.LocationServicePaymentXref lxref on ul.LocationId = lxref.LocationId and s.ServicePaymentId = lxref.ServicePaymentId
GROUP BY
s.State
, ServiceCenter
, s.LocationId
, s.ClientId
, c.LastName
, c.FirstName
, s.InvoiceId
, s.Quantity
, s.ItemDescription
, s.ServicePaymentId
, ul.ContractorName
Order by State, ServiceCenter, InvoiceNumber, LastName, FirstName, ItemDescription

see execution plan - maybe you need to add indexes
run query without sub-queries and see how long it will take then
try to split query to smaller parts (and run it separately) to find out which part slows query down

Related

Display Only More Than One Unique Customer/Address Per Truck Number

Been working on a project in which a report will generated from the SQL Query. I wish to display all Shipments (based on unique automatic truck ID) which contain any combination of:
Unique Customers (based on Customer Number, more than one Customer
Number per shipment)
Unique Addresses (based on defined Address Field, more than one unique
Address per shipment)
The output should look like this when the code runs correct:
Truck Customer First Address (other addresses) City State ZIP Country
12345 C12345 567 Hummingbird Lane Detroit MI 48610 US
12345 C12345 908 Elm Street Detroit MI 48611 US
12345 C78901 219 Maple Street Lansing MI 49012 US
Here is a sample of the code I been trying to tease out this information:
WITH cte
AS (SELECT DISTINCT shp.shipmentID
, ven.CustomerCode
, ven.CustomerName
, ads.FirstAddress
, ads.SecondAddress
, ads.ThirdAddress
, ads.City
, ads.State
, ads.Zip
, ads.Country
FROM
dbo.OrderItems AS ori
JOIN dbo.OrderLineProducts AS olns ON olns.olnID = ori.olnID
JOIN dbo.OrderLines AS oln ON oln.olnID = olns.olnID
JOIN dbo.Orders AS ord ON oln.ordID = ord.ordID
JOIN dbo.VendorCustomer AS ven ON ven.venID = ord.venID
JOIN dbo.OrderAddresses AS oa ON oa.ordID = ord.ordID
JOIN dbo.Address AS ads ON ads.addID = oa.addID
JOIN dbo.AddressType AS adst ON adst.atcID = ads.atcID
AND adst.atcAddressTypeCode = N'SHIP'
JOIN dbo.OrderItemShipments AS shpo ON ori.itmID = shpo.itmID
AND ori.itmIDInstance = shpo.itmIDInstance
AND ori.olnID = shpo.olnID
AND ori.olnIDInstance = shpo.olnIDInstance
JOIN dbo.Shipments AS shp ON shp.shipmentID = shpo.shpID
WHERE shpo.shpID = shp.shipmentID
AND ven.venCode IS NOT NULL
)
, maxadd
AS (SELECT
aa.venCode
, MAX(Multadd) AS Multadd
FROM (
SELECT
ROW_NUMBER() OVER (PARTITION BY cte.shipmentID, cte.CustomerCode ORDER BY cte.shipmentID) Multadd
, cte.shipmentID
, cte.CustomerCode
, cte.CustomerName
, cte.FirstAddress
, cte.SecondAddress
, cte.ThirdAddress
, cte.City
, cte.State
, cte.Zip
, cte.Country
FROM
cte
) AS aa
GROUP BY
aa.CustomerCode
HAVING COUNT (*)>1
)
, maxshp
AS (SELECT
cc.shipmentID
, MAX(cc.Multadd) AS MultVencode
FROM (
SELECT
bb.shipmentID
, bb.CustomerCode
, ROW_NUMBER() OVER (PARTITION BY shipmentID ORDER BY CustomerCode) Multadd
FROM (SELECT DISTINCT cte.shipmentID, cte.CustomerCode FROM cte) AS bb
) AS cc
GROUP BY
cc.shipmentID
HAVING COUNT(*) > 1
)
SELECT
cte.shipmentID
, cte.CustomerCode
, cte.CustomerName
, cte.FirstAddress
, cte.SecondAddress
, cte.ThirdAddress
, cte.City
, cte.State
, cte.Zip
, cte.Country
, maxadd.Multadd AS AddOnShipID
, maxshp.MultVencode AS VenOnShipID
FROM
cte
JOIN maxadd ON maxadd.CustomerCode = cte.CustomerCode
JOIN maxshp ON maxshp.shipmentID = cte.shipmentID
WHERE
(
maxadd.Multadd <> 2
AND maxshp.MultVencode <> 1
)
ORDER BY
cte.shipmentID
, cte.CustomerCode;
This "quasi" works. I have been racking my brain as to why this still is not working. Wondering if a second set of eyes may find something I am overlooking.
SELECT * FROM (SELECT DISTINCT shp.shipmentID
, ven.CustomerCode
, ven.CustomerName
, ads.FirstAddress
, ads.SecondAddress
, ads.ThirdAddress
, ads.City
, ads.State
, ads.Zip
, CASE WHEN(ads.Country LIKE 'US') THEN N'USA' ELSE 'CANADA' END AS Country
, COUNT (shp.shipmentID) OVER (PARTITION BY shipmentID ORDER BY shp.shpID) AS cntshpID
FROM dbo.OrderItems AS ori
JOIN dbo.OrderLineProducts AS olns ON olns.olnID = ori.olnID
JOIN dbo.OrderLines AS oln ON oln.olnID = olns.olnID
JOIN dbo.Orders AS ord ON oln.ordID = ord.ordID
JOIN dbo.VendorCustomer AS ven ON ven.venID = ord.venID
JOIN dbo.OrderAddresses AS oa ON oa.ordID = ord.ordID
JOIN dbo.Address AS ads ON ads.addID = oa.addID
JOIN dbo.AddressType AS adst ON adst.atcID = ads.atcID
AND adst.atcAddressTypeCode = N'SHIP'
JOIN dbo.OrderItemShipments AS shpo ON ori.itmID = shpo.itmID
AND ori.itmIDInstance = shpo.itmIDInstance
AND ori.olnID = shpo.olnID
AND ori.olnIDInstance = shpo.olnIDInstance
JOIN dbo.Shipments AS shp ON shp.shpID = shpo.shipmentID
WHERE shpo.shpID = shp.shipmentID
GROUP BY shp.shipmentID
, ven.CustomerCode
, ven.CustomerName
, ads.FirstAddress
, ads.SecondAddress
, ads.ThirdAddress
, ads.City
, ads.State
, ads.aZip
, ads.Country) AS bb
WHERE bb.cntshpID > 1
ORDER BY shpID ASC
CTE was not the way to go, it overcomplicated something simple.

sccm query cross apply outerapply doesnt give output

iam running SQL query which has cross apply and outer apply , i need state names as complaint , non complaint and pending system restart, but data iam getting is for all assignment id , please find query
SELECT cia.Assignment_UniqueID
, cia.AssignmentID
, cia.AssignmentName
, cia.EnforcementDeadline
, cia.StartTime
, sn.StateName
, NumberOfComputers = sc.StateCount
, Tot.TotalClientPerAssignment
, DeploymentStateID=sc.StateType*10000 + sc.StateID
, PComputers = cast(sc.StateCount * 100.00 / isnull(NULLIF (Tot.TotalClientPerAssignment, 0), 1) AS decimal(5, 2))
FROM v_CIAssignment cia
CROSS apply
(SELECT StateType, StateID, StateCount = count(*)
FROM v_AssignmentState_Combined
WHERE AssignmentID = cia.AssignmentID AND StateType IN (300, 301)
GROUP BY StateType, StateID) sc
CROSS apply
(SELECT DISTINCT TotalClientPerAssignment = count(atm.ResourceID) OVER (partition BY atm.assignmentid)
FROM v_CIAssignmentTargetedMachines atm
WHERE atm.AssignmentID = cia.AssignmentID) Tot
LEFT JOIN v_StateNames sn ON sn.TopicType = sc.StateType AND sn.StateID = sc.StateID
WHERE cia.AssignmentID = 2238
-- and sn.statename like '%Compliant%' or sn.statename like '%Pending system restart%'
and sn.statename like '%Compliant%' and sn.statename like '%restart%'
ORDER BY cia.AssignmentID, sc.StateCount DESC, sn.StateName
output iam getting is as follows
i need only statename as complaint , non complaint and pending restart for assignment id 2238 only but iam getting data for all assignment id
can you please help
output of query
This is because of your left join that's doesn't have any assignmentID
LEFT JOIN v_StateNames sn ON sn.TopicType = sc.StateType AND sn.StateID = sc.StateID
I suggest to use following query.
SELECT cia.Assignment_UniqueID
, cia.AssignmentID
, cia.AssignmentName
, cia.EnforcementDeadline
, cia.StartTime
, (SELECT StateName FROM v_StateNames WHERE TopicType = sc.StateType AND StateID = sc.StateID and statename like '%Compliant%' and statename like '%restart%') as StateName
, NumberOfComputers = sc.StateCount
, Tot.TotalClientPerAssignment
, DeploymentStateID=sc.StateType*10000 + sc.StateID
, PComputers = cast(sc.StateCount * 100.00 / isnull(NULLIF (Tot.TotalClientPerAssignment, 0), 1) AS decimal(5, 2))
FROM v_CIAssignment cia
CROSS apply
(SELECT StateType, StateID, StateCount = count(*)
FROM v_AssignmentState_Combined
WHERE AssignmentID = cia.AssignmentID AND StateType IN (300, 301)
GROUP BY StateType, StateID) sc
CROSS apply
(SELECT DISTINCT TotalClientPerAssignment = count(atm.ResourceID) OVER (partition BY atm.assignmentid)
FROM v_CIAssignmentTargetedMachines atm
WHERE atm.AssignmentID = cia.AssignmentID) Tot
WHERE cia.AssignmentID = 2238
ORDER BY cia.AssignmentID, sc.StateCount DESC

Substitute the Lag() function with another similiar option in Sybase

With the help of some of the users here in stackoverflow, I reached to the following query. The problem is that this query works well in SQL Server, but not in Sybase as it doesn't support LAG(). I have been trying to get it to work but no success.
The query is quite complicated but help in subsituting the LAG() function with something similar would be appreciated.
SELECT created
, bname
, total_share
FROM (
SELECT TT.created
, TT.bname
, TT.total_share
, lag(TT.total_share) OVER (
PARTITION BY TT.bname ORDER BY TT.created
) AS prev_share
FROM (
SELECT DISTINCT t.created AS created
, t.NAME AS bname
, t.total_share
FROM (
SELECT cast(fsp.created AS VARCHAR(19)) AS created
, e.NAME
, e.initials
, fsp.modified
, CASE
WHEN cl.price_per_item = 0
THEN CAST('' AS DECIMAL(18, 2))
ELSE CAST((fsp.new_price / cl.price_per_item * 100) AS DECIMAL(18, 2))
END AS new_share
, CASE
WHEN cl.price_per_item = 0
THEN CAST('' AS DECIMAL(18, 2))
ELSE CAST((prev / cl.price_per_item * 100) AS DECIMAL(18, 2))
END AS old_share
, fs.STATE
, CASE
WHEN fsp.prev_price IS NULL
THEN 0
ELSE fsp.prev_price
END AS prev
, fsp.new_price AS nprice
, (prev - nprice) AS diff
, new_share - old_share AS diff_share
, old_share + diff_share AS total_share
FROM project_manager pm
INNER JOIN dba.project p ON pm.project = p.id
LEFT JOIN dba.contract c ON p.id = c.project
LEFT JOIN dba.contract_line cl ON cl.contract = c.id
LEFT JOIN dba.product pt ON cl.product = pt.id
LEFT JOIN dba.specified_product sp ON sp.product = pt.id
LEFT JOIN dba.frozen_sale fs ON fs.spec_product = sp.id
AND fs.contract = c.id
AND fs.line = cl.idx
LEFT JOIN dba.frozen_sale_split fsp ON fsp.frozen_sale = fs.id
AND fsp.employee = pm.consultant
LEFT JOIN dba.employee e ON fsp.employee = e.person
LEFT JOIN dba.person ps ON fsp.creator = ps.id
WHERE p.id = 50000002735
AND e.NAME IS NOT NULL
) AS t
) TT /* here */
) x
WHERE (
prev_share IS NULL
OR prev_share total_share
)
ORDER BY created
, bname
The following code is untested, but the approach is to use the row_number window function to assign a sequential number (rnum in the code) to each row, ordered by the created value. This is done in the initial CTE. The main query then joins that CTE to itself, with a join condition of a difference of one in the rnum values.
with inp as (
SELECT TT.created
, TT.bname
, TT.total_share
, row_number over(order by TT.created) as rnum
FROM (
SELECT DISTINCT t.created AS created
, t.NAME AS bname
, t.total_share
FROM (
SELECT cast(fsp.created AS VARCHAR(19)) AS created
, e.NAME
, e.initials
, fsp.modified
, CASE
WHEN cl.price_per_item = 0
THEN CAST('' AS DECIMAL(18, 2))
ELSE CAST((fsp.new_price / cl.price_per_item * 100) AS DECIMAL(18, 2))
END AS new_share
, CASE
WHEN cl.price_per_item = 0
THEN CAST('' AS DECIMAL(18, 2))
ELSE CAST((prev / cl.price_per_item * 100) AS DECIMAL(18, 2))
END AS old_share
, fs.STATE
, CASE
WHEN fsp.prev_price IS NULL
THEN 0
ELSE fsp.prev_price
END AS prev
, fsp.new_price AS nprice
, (prev - nprice) AS diff
, new_share - old_share AS diff_share
, old_share + diff_share AS total_share
FROM project_manager pm
INNER JOIN dba.project p ON pm.project = p.id
LEFT JOIN dba.contract c ON p.id = c.project
LEFT JOIN dba.contract_line cl ON cl.contract = c.id
LEFT JOIN dba.product pt ON cl.product = pt.id
LEFT JOIN dba.specified_product sp ON sp.product = pt.id
LEFT JOIN dba.frozen_sale fs ON fs.spec_product = sp.id
AND fs.contract = c.id
AND fs.line = cl.idx
LEFT JOIN dba.frozen_sale_split fsp ON fsp.frozen_sale = fs.id
AND fsp.employee = pm.consultant
LEFT JOIN dba.employee e ON fsp.employee = e.person
LEFT JOIN dba.person ps ON fsp.creator = ps.id
WHERE p.id = 50000002735
AND e.NAME IS NOT NULL
) AS t
) TT
)
SELECT
created
, bname
, total_share
, prev.total_share as prev_share
FROM
inp
left join inp as prev on prev.rnum=inp.rnum-1
and prev.bname=inp.bname
WHERE (
prev.total_share IS NULL
OR prev.total_share total_share
)
ORDER BY
created
, bname

sql sum() causing doubling of values with left outer join

The left out join on dbo.SalespersonProject is causing the value for TranAmt to double. I need to sum the legit TranAmt for projects, but adding in the left outer join and SalesPerson02, causes a match an incorrect doubling.
SELECT ARDoc.SlsperId AR_Doc_Sls_ID
, CASE
WHEN ARTran.TranType = 'CM' THEN SUM(ARTran.TranAmt) * -1
ELSE SUM(ARTran.TranAmt)
END TranAmt
, MAX(CASE
WHEN SalesCommOrder = 1 THEN SalesPersonId
END) Salesperson01
, MAX(ISNULL(CASE
WHEN SalesCommOrder = 1 THEN Percentage
END, .03)) Commission01
, MAX(CASE
WHEN SalesCommOrder = 2 THEN SalesPersonId
END) Salesperson02
, MAX(CASE
WHEN SalesCommOrder = 2 THEN Percentage
END) Commission02
, PJPROJ.project PJ_ID
, PJPROJ.project_desc PJ_Description
, PJPROJ.slsperid SME
, ARDoc.CustId Cust_ID
, CASE
WHEN RTRIM(ARTran.InvtId) = 'GRAPHICS' THEN 1
WHEN RTRIM(ARTran.InvtID) = 'SERVICE CONTRACT' THEN 2
END InvtID
, RTRIM(ARDoc.CustId) + ' ' + Customer.BillName Cust_ID_Name
, CONVERT( DATE, ARTran.TranDate, 101) Doc_Date
, ARTran.TranType Doc_Type
, ARTran.RefNbr
, PJPROJ.start_date
, SUM(ARTran.ExtCost) ExtCost
, SUM(ARTran.UnitPrice) UnitPrice
, SUM(ARTran.Qty) Qty
, (
SELECT SUM(b.eac_amount) [Budg Rev]
FROM pjptdsum b
INNER JOIN pjacct a ON a.acct = b.acct
AND a.acct_type = 'RV'
WHERE ARDoc.ProjectID = b.project) Budget_Rev
, (
SELECT SUM(b.eac_amount) [Budg Rev]
FROM pjptdsum b
INNER JOIN pjacct a ON a.acct = b.acct
AND a.acct_type = 'EX'
WHERE ARDoc.ProjectID = b.project) Budget_EAC
, so.TotMerch SalesOrderTotal
, Salesperson.Name
, ARTran.PerPost
, PJPROJ.manager2
, PJEMPLOY.emp_name
FROM Testnewgroundapp.dbo.ARDoc ARDoc
INNER JOIN Testnewgroundapp.dbo.ARTran ARTran ON ARDoc.CustId = ARTran.CustId
AND ARDoc.RefNbr = ARTran.RefNbr
AND ARDoc.DocType = ARTran.TranType
INNER JOIN Testnewgroundapp.dbo.Customer Customer ON ARDoc.CustId = Customer.CustId --INNER JOIN #CustomerTab ct
LEFT OUTER JOIN Testnewgroundapp.dbo.Salesperson Salesperson ON ARDoc.SlsperId = Salesperson.SlsperId
LEFT OUTER JOIN Testnewgroundapp.dbo.PJPROJ PJPROJ ON ARDoc.ProjectID = PJPROJ.project
LEFT OUTER JOIN Testnewgroundapp.dbo.PJEMPLOY PJEMPLOY ON PJPROJ.manager2 = PJEMPLOY.employee
LEFT OUTER JOIN (
SELECT h.PerPost
, h.SlsperID
, SUM(h.TotMerch) TotMerch
FROM SOShipHeader H
GROUP BY h.PerPost
, h.SlsperID) so ON ARTran.PerPost = so.PerPost
AND ARDoc.SlsperId = so.SlsperID
LEFT OUTER JOIN TestCommissions.dbo.SalespersonProject SalespersonProject ON SalespersonProject.ProjectId = PJPROJ.project --AND SalespersonProject.SalesPerson_Id = #ApplicationUserID
LEFT OUTER JOIN TestCommissions.dbo.SalesPerson AppSalesPerson ON AppSalesPerson.Id = SalespersonProject.SalesPerson_Id
WHERE
(ARTran.TranType = 'CM'
AND ARTran.DrCr = 'D'
OR ARTran.DrCr = 'C'
AND
(ARTran.TranType = 'CS'
OR ARTran.TranType = 'DM'
OR ARTran.TranType = 'IN'
)
)
AND ARTran.TaskID NOT LIKE '%60850'
AND ARTRan.TaskID NOT LIKE '%60900'
AND ARTran.invtid <> 'TSCINC001'
AND ARTran.TranClass NOT IN ('F', 'N', 'T')
AND ARTran.Acct NOT IN ('2590', '2040', '2037')
AND CONVERT(INT, ARTran.Acct) > 1301
AND CONVERT(INT, ARTran.PerPost) BETWEEN 201504 AND 201504
AND ARTran.Rlsed = 1
AND PJPROJ.project IS NOT NULL
AND artran.cpnyid IN ('R', 'A')
GROUP BY ARDoc.SlsperId
, ARDoc.ProjectID
, PJPROJ.project
, PJPROJ.project_desc
, PJPROJ.slsperid
, ARDoc.CustId
, ARTran.InvtId
, Customer.BillName
, ARTran.TranDate
, ARTran.TranType
, ARTran.RefNbr
, PJPROJ.start_date
, so.TotMerch
, Salesperson.Name
, ARTran.PerPost
, ARDoc.CpnyID
, PJPROJ.manager2
, PJEMPLOY.emp_name
HAVING ARDoc.SlsperId = 'bpettit'
ORDER BY ARDoc.SlsperId, ARTran.PerPost, PJPROJ.project
If an extra joined table has two records per one main record, this makes each main record appear twice in the result set. The following grouping and summing will then sum each value of the main record or another joined table twice.
Temporarily remove the grouping and summing, but keep all the joins and look at the result set. You will then probably see what causes this doubling.

Sql Server - 2 queries executed together takes longer

I have 2 queries.
Query # 1: inserts some data into a temp table
Query # 2: inserts the data from the temp table (with some joins) into a new table.
Running Query #1 alone takes 3 seconds. Running Query #2 alone takes 12 seconds.
When I run them both together as one execution, it runs forever (over 4 minutes).
What could possibly be the reason for this?
(I would post my code but it's very long and not much understandable to the outsider.)
Here's my SQL (at your own risk): Remember they run fine when ran alone.
-- START QUERY #1
SELECT * INTO #TempProdForSiteGoingTrim
FROM
(
SELECT
p.idProduct
, p.active
, p.sku
, p.description
, p.listprice
, p.price
, p.imageurl
, p.smallimageurl
, p.idManufacturer
, sortOrder
, CASE WHEN p.pgroup = '' OR p.pgroup IS NULL THEN CAST(p.idProduct AS VARCHAR) ELSE pgroup END [pgroup]
, CASE WHEN pa2.attr IS NULL THEN CAST(p.idProduct AS VARCHAR) ELSE CASE WHEN p.pgroup = '' OR p.pgroup IS NULL THEN CAST(p.idProduct AS VARCHAR) ELSE pgroup END END [RugGroup]
, pa1.attr [Color]
, pa3.attr [Collection]
, pa2.attr [RugSize]
, pa4.attr[RugShape]
FROM
(SELECT DISTINCT idProduct FROM ProdSite WHERE idSite = 39 ) s
INNER JOIN (SELECT * FROM products p WHERE active = -1 ) p ON s.idproduct = p.idproduct
LEFT OUTER JOIN (SELECT t.idproduct, attr FROM (SELECT max(idprodattr) [idprodattr], idproduct, b.idattrset FROM productattr a JOIN product_attr b on a.idattr = b.idattr WHERE idattrset = 1 GROUP BY a.idproduct, b.idattrset )t JOIN productattr a ON t.idprodattr = a.idprodattr JOIN product_attr b ON a.idattr = b.idattr) pa1 ON p.idproduct = pa1.idproduct
LEFT OUTER JOIN (SELECT t.idproduct, attr FROM (SELECT max(idprodattr)[idprodattr], idproduct, b.idattrset FROM productattr a JOIN product_attr b on a.idattr = b.idattr WHERE idattrset = 160 GROUP BY a.idproduct, b.idattrset )t JOIN productattr a ON t.idprodattr = a.idprodattr JOIN product_attr b ON a.idattr = b.idattr) pa2 ON p.idproduct = pa2.idproduct
LEFT OUTER JOIN (SELECT t.idproduct, attr FROM (SELECT max(idprodattr)[idprodattr], idproduct, b.idattrset FROM productattr a JOIN product_attr b on a.idattr = b.idattr WHERE idattrset = 6 GROUP BY a.idproduct, b.idattrset )t JOIN productattr a ON t.idprodattr = a.idprodattr JOIN product_attr b ON a.idattr = b.idattr) pa3 ON p.idproduct = pa3.idproduct
LEFT OUTER JOIN (SELECT t.idproduct, attr FROM (SELECT max(idprodattr)[idprodattr], idproduct, b.idattrset FROM productattr a JOIN product_attr b on a.idattr = b.idattr WHERE idattrset = 62 GROUP BY a.idproduct, b.idattrset )t JOIN productattr a ON t.idprodattr = a.idprodattr JOIN product_attr b ON a.idattr = b.idattr) pa4 ON p.idproduct = pa4.idproduct
)t
-- END QUERY #1
-- START QUERY #2
DECLARE #listRugSizes TABLE (idmanufacturer int, RugGroup VARCHAR(500), RugSizes VARCHAR(1000))
INSERT INTO #listRugSizes
SELECT
t1.idmanufacturer
, t1.RugGroup
, STUFF(( SELECT ', ' + RugSize FROM #TempProdForSiteGoingTrim t2 WHERE t2.RugGroup = t1.RugGroup and t2.idmanufacturer = t1.idmanufacturer FOR XML PATH(''), TYPE ).value('.', 'varchar(max)'), 1, 1, '') [Values]
FROM
#TempProdForSiteGoingTrim t1
GROUP BY
t1.RugGroup
, t1.idmanufacturer
INSERT INTO [NewTableForSiteGoingTrim]
SELECT
p.idProduct
, p.sku
, p.description
, p.listPrice
, p.price
, p.imageUrl
, p.smallImageUrl
, p.sortOrder
, p.idManufacturer
, p.pgroup
, p.ruggroup
, c.idCategory
, c.idCategory [fidcategory]
, c.idParentCategory
, c.idParentCategory [gidcategory]
, pc.idParentCategory [hidCategory]
, ppc.idParentCategory [iidCategory]
, m.Name
, rp.rewrite_key [rewrite_index]
, rm.rewrite_key [rewrite_key]
, color [Color]
, collection [Collection]
, rugsize [RugSize]
, ruggroup.rugcount
, ruggroup.maxprice
, ruggroup.minprice
, rs.RugSizes
, p.rugshape
FROM
#TempProdForSiteGoingTrim p
LEFT OUTER JOIN (
SELECT
MIN(c.idCategory) [idCategory]
, c.idProduct
FROM
(
SELECT
cp.idProduct
, cp.idCategory
FROM
dbo.categories_products cp
JOIN categories c ON cp.idcategory = c.idCategory
WHERE
c.idSite = 24
) c
GROUP BY
c.idProduct
) cp ON p.idProduct = cp.idProduct
LEFT OUTER JOIN categories c ON cp.idCategory = c.idCategory
LEFT OUTER JOIN categories pc ON c.idParentCategory = pc.idCategory
LEFT OUTER JOIN categories ppc ON pc.idParentCategory = ppc.idCategory
LEFT OUTER JOIN manufacturer m ON p.idManufacturer = m.idManufacturer
LEFT OUTER JOIN (SELECT * FROM rewrite WHERE type = 3) rm ON p.idManufacturer = rm.id
LEFT OUTER JOIN (SELECT * FROM rewrite WHERE type = 1) rp ON p.idProduct = rp.id
LEFT OUTER JOIN #listRugSizes rs ON p.RugGroup = rs.RugGroup and p.idmanufacturer = rs.idmanufacturer
LEFT OUTER JOIN
(
SELECT
p.ruggroup
, p.idmanufacturer
, min(price) [minPrice]
, count(*) [RugCount]
, m.maxprice
FROM
#TempProdForSiteGoingTrim p
LEFT OUTER JOIN
(
SELECT
r.ruggroup
, r.idmanufacturer
, max(price) [maxprice]
FROM
#TempProdForSiteGoingTrim r
WHERE
r.idproduct = (SELECT MAX(idproduct) FROM #TempProdForSiteGoingTrim WHERE ruggroup = r.ruggroup AND price = r.price and idmanufacturer = r.idmanufacturer)
GROUP BY
ruggroup
, idmanufacturer
) m ON p.ruggroup = m.ruggroup and p.idmanufacturer = m.idmanufacturer
GROUP BY
p.ruggroup
, m.maxprice
, p.idmanufacturer
) ruggroup ON p.ruggroup = ruggroup.ruggroup and p.idmanufacturer = ruggroup.idmanufacturer
-- END QUERY #2
Edit
When I change the last join "ruggroup" to only group and join by column "ruggroup" and not "ruggroup" and "idmanufacturer" then it works fine.