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

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

Related

Use CTE in SQL to flag DUPLICATES and reference in sub-query

So I have the following CTE:
with dupeinv AS (
select * from (
select
tci.t_idoc,
tci.t_idat,
ROW_NUMBER() OVER (partition by tci.t_idoc ORDER BY tci.t_idoc, tci.t_idat DESC) as rn
from [ln106].[dbo].tcisli305100 tci
) as t
where t.rn = 1
)
There are duplicates in the above table ([ln106].[dbo].tcisli305100) , hence the CTE to get single values. I want to format just these values in the below query (prefixed with ---)
select 'JCI' as BU,
RTRIM(LTRIM(cl.t_orno)) AS SALES_ORDER_NUMBER
, cl.t_pono AS SALES_ORDER_LINE_NUMBER
, CONCAT(cl.t_shpm, cl.t_pono, cl.t_idoc) AS SHIPPING_RECORD_ID
,CASE WHEN cl.t_dqua = 0 or cl.t_dqua is null THEN cl.t_amti ELSE
cl.t_amti / cl.t_dqua END AS AR_INVOICE_LINE_ITEM_PRICE_LOCAL
, cl.t_line AS AR_INVOICE_LINE_NUMBER
, cl.t_dqua AS AR_INVOICE_LINE_ITEM_QUANTITY
--- , concat(dupeinv.t_idoc,'|',format(dupeinv.t_idat,'MMddyyyy') ---
,ci.t_ccur AS AR_INVOICE_CURRENCY
, ci.t_idat AS AR_INVOICE_DATE
FROM [ln106].[dbo].tcisli310100 cl
LEFT JOIN [ln106].[dbo].tcisli305100 ci ON cl.t_idoc = ci.t_idoc
LEFT JOIN t di on cl.t_doc = di_t_doc
LEFT JOIN (SELECT t_orno,t_pono FROM [ln106].[dbo].ttdsls401100 WHERE t_oltp <> 1 group by t_orno,t_pono) as l --Jed 10162020 Changed the join to prevent duplicate records
ON l.t_orno=cl.t_orno COLLATE SQL_Latin1_General_CP1_CI_AS AND l.t_pono=cl.t_pono
LEFT JOIN dupeinv tci on cl.r_idoc = ci.t_doc
WHERE ci.t_idat > '2017'
Query doesn't like me referencing it in the main query. Can anyone help, or suggest a better idea?
Your final query should look something like this:
WITH dupeinv AS
(SELECT *
FROM
(SELECT tci.t_idoc,
tci.t_idat,
ROW_NUMBER() OVER (PARTITION BY tci.t_idoc
ORDER BY tci.t_idoc,
tci.t_idat DESC) AS rn
FROM [ln106].[dbo].tcisli305100 tci) AS t
WHERE t.rn = 1 )
SELECT 'JCI' AS BU,
RTRIM(LTRIM(cl.t_orno)) AS SALES_ORDER_NUMBER ,
cl.t_pono AS SALES_ORDER_LINE_NUMBER ,
CONCAT(cl.t_shpm, cl.t_pono, cl.t_idoc) AS SHIPPING_RECORD_ID ,
CASE
WHEN cl.t_dqua = 0
OR cl.t_dqua IS NULL THEN cl.t_amti
ELSE cl.t_amti / cl.t_dqua
END AS AR_INVOICE_LINE_ITEM_PRICE_LOCAL ,
cl.t_line AS AR_INVOICE_LINE_NUMBER ,
cl.t_dqua AS AR_INVOICE_LINE_ITEM_QUANTITY ,
concat(dupeinv.t_idoc,
'|',
format(dupeinv.t_idat, 'MMddyyyy')) ,
ci.t_ccur AS AR_INVOICE_CURRENCY ,
ci.t_idat AS AR_INVOICE_DATE
FROM [ln106].[dbo].tcisli310100 cl
LEFT JOIN [ln106].[dbo].tcisli305100 ci ON cl.t_idoc = ci.t_idoc
LEFT JOIN t di ON cl.t_doc = di_t_doc
LEFT JOIN
(SELECT t_orno,
t_pono
FROM [ln106].[dbo].ttdsls401100
WHERE t_oltp <> 1
GROUP BY t_orno,
t_pono) AS l --Jed 10162020 Changed the join to prevent duplicate records
ON l.t_orno=cl.t_orno COLLATE SQL_Latin1_General_CP1_CI_AS
AND l.t_pono=cl.t_pono
LEFT JOIN dupeinv tci ON cl.r_idoc = ci.t_doc
WHERE ci.t_idat > '2017'

This SQL query is taking too long

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

How to add Parameter to report

select distinct sotr_sys_no
, SODETS_VINYL_COLOUR
, SODETS_MDF_COLOUR
, SOTR_PROMISED_DATE
, DATEDIFF(dd,getdate(),sotr_promised_date) as DueDays
, AEXTRA_5_SHORT_NAME
, AEXTRA_5_VINYL_PARTCODE
, CASE WHEN SODETS_MDF_COLOUR > '0' THEN AltMDFCode ELSE AEXTRA_5_MDF_PARTCODE END AS AEXTRA_5_MDF_PARTCODE
, ISNULL(Vinylqty,0) As VinylQty
, ISNULL(MDFqty,0) as MDFQty
, Vinyldue
, MDFdue
, WO.WOOutstanding
from Defactouser.F_SO_Transaction WITH (NOLOCK)
inner join defactouser.F_SO_Transaction_Details WITH (NOLOCK)
on sotr_sys_no = sotd_head_no
inner join defactouser.F_SO_Transaction_Details_Extra WITH (NOLOCK)
on SOTD_SYS_NO = SODETS_LINK
left outer join (
select distinct AEXTRA_5_CODE as AltMDFKey
, AEXTRA_5_MDF_PARTCODE AS AltMDFCode
from DeFactoUser.F_AD_Extra_5 WITH (NOLOCK)
) as AltMDF
on SODETS_MDF_COLOUR = AltMDF.AltMDFKey
left outer join defactouser.F_AD_Extra_5 WITH (NOLOCK)
on SODETS_VINYL_COLOUR = [AEXTRA_5_CODE]
inner join defactouser.F_ST_Products WITH (NOLOCK)
on sotd_strc_code = strc_code
left Outer join (
SELECT Product_Code As VinylStockCode, sum(Physical_Qty_Units) as Vinylqty FROM DBO.DFBI_Stock_Physical WITH (NOLOCK)
WHERE Warehouse = 'DOORS' and LEFT(product_code ,3) = 'vfl'
Group By Product_Code
HAVING SUM(Physical_Qty_Units) >0
) VinylStock
on AEXTRA_5_VINYL_PARTCODE = VinylStock.VinylStockCode
left outer join (
SELECT Product_Code As MDFStockCode, sum(Physical_Qty_Units) as MDFqty FROM DBO.DFBI_Stock_Physical WITH (NOLOCK)
WHERE Warehouse = 'PANELS' and LEFT(product_code ,3) = 'MDF'
Group By Product_Code
HAVING SUM(Physical_Qty_Units) >0
) MDFStock
on CASE WHEN SODETS_MDF_COLOUR > '0' THEN AltMDF.AltMDFCode ELSE AEXTRA_5_MDF_PARTCODE END = MDFStock.MDFStockCode
left Outer JOin (select stex_strc_code as VinylStex , sum(STEX_QTY_UNITS) as Qty, MIN(stex_promised_date) as Vinyldue
from defactouser.F_ST_Transaction_Expediting
where left(stex_strc_code ,3) = 'vfl'
and stex_type = 'pop+'
group By STEX_STRC_CODE
) VinylStockIn
on AEXTRA_5_VINYL_PARTCODE = VinylStex
left Outer Join (
select stex_strc_code as MDFStex , sum(STEX_QTY_UNITS) as Qty, MIN(stex_promised_date) as MDFdue
from defactouser.F_ST_Transaction_Expediting
where left(stex_strc_code ,3) = 'mdf'
and stex_type = 'pop+'
group By STEX_STRC_CODE
) MDFStockIn on CASE WHEN SODETS_MDF_COLOUR > '0' THEN AltMDF.AltMDFCode ELSE AEXTRA_5_MDF_PARTCODE END = MDFStex
LEFT OUTER JOIN (
select SOTD_HEAD_NO, SODETS_VINYL_COLOUR as WOVinyl, SUM(BMTD_QTY_OUTSTANDING) as WOOutstanding from defactouser.f_bm_transactions_details
inner join defactouser.F_SO_Transaction_Details on BMTD_ORDER_LINK_NUMBER = SOTD_SYS_NO
inner join defactouser.F_SO_Transaction_Details_Extra on BMTD_ORDER_LINK_NUMBER = SODETS_LINK
where bmtd_type = 1 and bmtd_bmtr_type = 0 and bmtd_stwh_code in ('doors', 'shef trans') and SOTD_STATUS <99
Group by SOTD_HEAD_NO, SODETS_VINYL_COLOUR
) WO
on sotr_sys_no = WO.SOTD_HEAD_NO AND SODETS_VINYL_COLOUR = WO.WOVinyl
where (SOTD_QTY_UNITS_OUTSTANDING > 0
and SOTR_TYPE = 10
and SOTD_STWH_CODE IN ('doors' , 'hpp shef')
and left(sotd_strc_code ,5) <> 'drill'
and SOTR_CUST_CODE <>'hpp'
and STRC_ANAL1 = '1027'
and ISNULL(VinylQty,0) <10
and DATEDIFF(dd,getdate(),sotr_promised_date) <5
)
or
(SOTD_QTY_UNITS_OUTSTANDING > 0
and SOTR_TYPE = 10
and SOTD_STWH_CODE IN ('doors' , 'hpp shef')
and left(sotd_strc_code ,5) <> 'drill'
and SOTR_CUST_CODE <>'hpp'
and STRC_ANAL1 = '1027'
and ISNULL(MDFQty,0) <4
and DATEDIFF(dd,getdate(),sotr_promised_date) <5
)
Order By MDFQty, AEXTRA_5_MDF_PARTCODE
Currently this query produces a report that returns a table with products due to arrive in the next 5 days. How do I add a parameter to the report that will show me the results as it is, and then also to show a report for products due in whenever. I am using Report Builder 3.0, and have tried to add a parameter but cannot get the desired result.
Can this be done without editing the query and just in report builder?
Change you WHERE clause and replace < 5 with < #Days. Assuming the query is not a stored proc and is directly in the dataset query then SSRS will automatically add the #Days parameter to your report.

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.