How to Update field using subquery with aliases - sql

I have an Update query that will help me to update a certain field and right now it is throwing an error on the last two lines of code where the d.column is mentioned. Does anyone know how I can still use the d.column fields at the end or know a work around that will produce the same results? Help is greatly appreciated. The error is where I am using d.LastUpdateSchedule and d.Due_Dte in the last two lines of code.
update ods.Customer
set NumberTPD = a.NumberCode
from ods.Customer r
left join
(
Select d.CustomerNumber
, d.due_Dte
, l.NumberCode
from (select r.CustomerNumber
, r.due_Dte
, r.NumberTPD
, max(l.UpdateSchedule) as LastUpdateSchedule
from ods.Customer r
left join ods.CustomerHistory l
on r.CustomerNumber = l.CustomerNumber
and r.due_Dte >= l.UpdateSchedule
and l.Examine = 1
and r.ExamineFrequency in ('MONTHLY','MNTHLYLDAY')
and isnull(r.ScheduleEndDate,'1970-01-01') < r.due_Dte
group by r.CustomerNumber, r.Due_Dte, r.NumberTPD) d
left join ods.CustomerHistory l
on d.CustomerNumber = l.CustomerNumber
and d.LastUpdateSchedule = l.UpdatedSchedule
) a
on r.CustomerNumber = a.CustomerNumber
and r.Due_Dte = a.Due_Dte
where d.Due_Dte > '2018-08-03'
and d.LastUpdateSchedule is not null

this is because your table d is inside your table a move your where clause to table d
update ods.Customer
set NumberTPD = a.NumberCode
from ods.Customer r
left join
(Select d.CustomerNumber
, d.due_Dte
, l.NumberCode
from
(select r.CustomerNumber
, r.due_Dte
, r.NumberTPD
, max(l.UpdateSchedule) as LastUpdateSchedule
from ods.Customer r
left join ods.CustomerHistory l on r.CustomerNumber = l.CustomerNumber
and r.due_Dte >= l.UpdateSchedule
and l.Examine = 1
and r.ExamineFrequency in ('MONTHLY','MNTHLYLDAY')
and isnull(r.ScheduleEndDate,'1970-01-01') < r.due_Dte
group by r.CustomerNumber, r.Due_Dte, r.NumberTPD) d
left join ods.CustomerHistory l on d.CustomerNumber = l.CustomerNumber
and d.LastUpdateSchedule = l.UpdatedSchedule
where d.Due_Dte > '2018-08-03'
and d.LastUpdateSchedule is not null
) a on r.CustomerNumber = a.CustomerNumber
and r.Due_Dte = a.Due_Dte

-- only what you need
UPDATE cust
SET cust.NumberTPD = histRow.NumberCode
FROM ods.Customer cust
JOIN
(SELECT c.CustomerNumber,
max(h.UpdateSchedule) AS LastUpdateSchedule
FROM ods.Customer c
JOIN ods.CustomerHistory h ON c.CustomerNumber = h.CustomerNumber
AND c.due_Dte >= h.UpdateSchedule
WHERE c.Due_Dte > '2018-08-03'
AND c.ExamineFrequency IN ('MONTHLY',
'MNTHLYLDAY')
AND isnull(c.ScheduleEndDate, '1970-01-01') < c.due_Dte --sure about this?
AND h.Examine = 1
GROUP BY c.CustomerNumber) maxes
JOIN ods.CustomerHistory histRow ON maxes.CustomerNumber = histRow.CustomerNumber
AND maxes.LastUpdateSchedule = histRow.UpdatedSchedule

Related

Having count returning zero rows when it should return something

SELECT
P.P_DESC AS P,
D.PD_NAME AS D,
D.GPE_NBR AS GPE,
D.GPE_GEN_NM,
D.GPE_2_ ,
D.GPE_4c ,
SUBSTR (TRIM(C.FILL_DATE__ID),1,6),
C.fill_Date__ID,
Prod.PD_DESC ,
DMC.M_A_NBR,
DMC.MAD_NBR ,
DMC.FT_NAME,
DMC.LA_NAME,
DDB.DATE_DATE,
CAST((CURRENT_DATE - DDB.DATE_DATE)/365.25 as Int) M_AGE_TODAY,
RXDOC.PB_FT_NAME || ' ' || RXDOC.PB_LA_NAME ,
RXDOC.PB_ID,
DT.D_TYPE_DESC ,
CASE WHEN SDL.GEPE IS NOT NULL THEN 'Y' ELSE 'N' END AS FLAG,
COUNT (C.PHR_C_ID) AS CCount,
SUM (C.AMT_PAID) AS Spend
FROM O_PHAR_C C
INNER JOIN _D D ON C.D__ID=D.D__ID
INNER JOIN _P P
ON C.P__ID = P.P__ID
AND C.P__ID = 00001
INNER JOIN _M_CURR DMC ON C.PB_M_CURR_ID = DMC.M_CURR_ID
INNER JOIN _M DM ON DM.M__ID = DMC.M__ID
INNER JOIN _DATE DDB ON DDB.DATE__ID = DM.BIRTH_DATE__ID
INNER JOIN _M_ELIG_CURR DMEC ON C.PB_M_ELIG_CURR_ID = DMEC.M_ELIG_CURR_ID
LEFT OUTER JOIN BA_PROD_LAB_OWN.specialtyDList SDL
ON D.GPE_NBR = SDL.GPE
AND SDL.EFF_END_DATE >= CURRENT_DATE
LEFT OUTER JOIN _PD Prod ON DMEC.PD__ID = Prod.PD__ID
LEFT OUTER JOIN _RX_PB RXDOC ON C.PB__ID=RXDOC.PB__ID
LEFT OUTER JOIN _PHAR_D_TYPE DT ON C.PHAR_D_TYPE__ID = DT.PHAR_D_TYPE__ID
WHERE C.fill_date__ID BETWEEN 20170201 AND 20170228
AND C.RE_I = 'N'
AND C.sR__ID IN (96,13,203)
GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13,14, 15, 16, 17, 18, 19
HAVING COUNT(*) >= 10;
I want to use this query to return instances of the C.PHR_C_ID that are more than or equal to 10. However, when I limit my select statement to that column I get the desired result but when I add all these columns to it 'having count' returns 0. There are more than zero records; I think there is something wrong with the query.
The problem is that when you add in your fields and GROUP BY them, you get a count of records for that distinct list of fields. You can probably switch to a QUALIFY statement instead. This will sum up the results by distinct C.PHR_C_ID ignoring the other fields, and then return any fields for that distinct C.PHR_C_ID which has a count(*) >= 10.
SELECT
P.P_DESC AS P,
D.PD_NAME AS D,
D.GPE_NBR AS GPE,
D.GPE_GEN_NM,
D.GPE_2_ ,
D.GPE_4c ,
SUBSTR (TRIM(C.FILL_DATE__ID),1,6),
C.fill_Date__ID,
Prod.PD_DESC ,
DMC.M_A_NBR,
DMC.MAD_NBR ,
DMC.FT_NAME,
DMC.LA_NAME,
DDB.DATE_DATE,
CAST((CURRENT_DATE - DDB.DATE_DATE)/365.25 as Int) M_AGE_TODAY,
RXDOC.PB_FT_NAME || ' ' || RXDOC.PB_LA_NAME ,
RXDOC.PB_ID,
DT.D_TYPE_DESC ,
CASE
WHEN SDL.GEPE IS NOT NULL THEN 'Y'
ELSE 'N'
END AS FLAG,
COUNT(*) OVER (PARTITION BY C.PHR_C_ID) AS CCount,
C.AMT_PAID AS Spend
FROM O_PHAR_C C
INNER JOIN _D D
ON C.D__ID=D.D__ID
INNER JOIN _P P
ON C.P__ID = P.P__ID
AND C.P__ID = 00001
INNER JOIN _M_CURR DMC
ON C.PB_M_CURR_ID = DMC.M_CURR_ID
INNER JOIN _M DM
ON DM.M__ID = DMC.M__ID
INNER JOIN _DATE DDB
ON DDB.DATE__ID = DM.BIRTH_DATE__ID
INNER JOIN _M_ELIG_CURR DMEC
ON C.PB_M_ELIG_CURR_ID = DMEC.M_ELIG_CURR_ID
LEFT OUTER JOIN BA_PROD_LAB_OWN.specialtyDList SDL
ON D.GPE_NBR = SDL.GPE
AND SDL.EFF_END_DATE >= CURRENT_DATE
LEFT OUTER JOIN _PD Prod
ON DMEC.PD__ID = Prod.PD__ID
LEFT OUTER JOIN _RX_PB RXDOC
ON C.PB__ID=RXDOC.PB__ID
LEFT OUTER JOIN _PHAR_D_TYPE DT
ON C.PHAR_D_TYPE__ID = DT.PHAR_D_TYPE__ID
WHERE
C.fill_date__ID BETWEEN 20170201 AND 20170228
AND C.RE_I = 'N'
AND C.sR__ID IN (96,13,203)
QUALIFY COUNT(*) OVER (PARTITION BY C.PHR_C_ID) >= 10;

Multiple SQL JOIN with multiple criteria

SELECT A.SspStudent,
B.StuLastName,
B.StuFirstName,
C.TerDescription,
A.SspCourseSubject,
A.SspCourseID,
A.SspCreditHours,
A.SspStatus,
B.StuEmailUNCW,
B.StuAdvisorEmail,
B.StuApplicationStatus,
D.UseName
FROM ((tblStudentSchedulePerm A
INNER JOIN tblStudent B
ON (A.SspStudent = B.StuID AND
B.StuAdmitTerm <> '201520A' AND
A.SspStatus = 'Schedul' AND
(A.SspTerm = '201520A' OR A.SspTerm = '201520B') AND
A.SspCreditHours <> 0))
LEFT OUTER JOIN tblTerms C
ON A.SspTerm = C.TerTermPart)
LEFT OUTER JOIN D tblUser
ON B.StuAdvisorEmail = D.UseEmail;
I am trying to make this query work but everytime I try to adjust the parenthesis I get an error.
Could I get some help??
you are better off, with out those parenthesis, also you need to a sub query in the joins
Retained the parenthesis except in the OR AND condition , try this out.
SELECT A.SspStudent,
B.StuLastName,
B.StuFirstName,
C.TerDescription,
A.SspCourseSubject,
A.SspCourseID,
A.SspCreditHours,
A.SspStatus,
B.StuEmailUNCW,
B.StuAdvisorEmail,
B.StuApplicationStatus,
D.UseName
FROM tblStudentSchedulePerm A
INNER JOIN tblStudent B
ON A.SspStudent = B.StuID
AND B.StuAdmitTerm <> '201520A'
AND A.SspStatus = 'Schedul'
AND ( A.SspTerm = '201520A'
OR A.SspTerm = '201520B' )
AND A.SspCreditHours <> 0
LEFT OUTER JOIN tblTerms C
ON A.SspTerm = C.TerTermPart
LEFT OUTER JOIN tblUser D
ON B.StuAdvisorEmail = D.UseEmail;
I indented your query. This is how I usually start to pick apart something with which I'm unfamilar.
SELECT
A.SspStudent
, B.StuLastName
, B.StuFirstName
, C.TerDescription
, A.SspCourseSubject
, A.SspCourseID
, A.SspCreditHours
, A.SspStatus
, B.StuEmailUNCW
, B.StuAdvisorEmail
, B.StuApplicationStatus
, D.UseName
FROM
(
(
tblStudentSchedulePerm A
INNER JOIN tblStudent B ON
(
A.SspStudent = B.StuID
AND B.StuAdmitTerm <> '201520A'
AND A.SspStatus = 'Schedul'
AND (A.SspTerm = '201520A' OR A.SspTerm = '201520B')
AND A.SspCreditHours <> 0
)
)
LEFT OUTER JOIN tblTerms C ON A.SspTerm = C.TerTermPart
)
LEFT OUTER JOIN D tblUser ON B.StuAdvisorEmail = D.UseEmail
;
D tblUser
should be :
tblUser D
Other than that, remove all useless parentheses:
SELECT A.SspStudent,
B.StuLastName,
B.StuFirstName,
C.TerDescription,
A.SspCourseSubject,
A.SspCourseID,
A.SspCreditHours,
A.SspStatus,
B.StuEmailUNCW,
B.StuAdvisorEmail,
B.StuApplicationStatus,
D.UseName
FROM tblStudentSchedulePerm A
INNER JOIN tblStudent B
ON A.SspStudent = B.StuID
AND B.StuAdmitTerm <> '201520A'
AND A.SspStatus = 'Schedul'
AND ( A.SspTerm = '201520A'
OR A.SspTerm = '201520B' )
AND A.SspCreditHours <> 0
LEFT OUTER JOIN tblTerms C
ON A.SspTerm = C.TerTermPart
LEFT OUTER JOIN tblUser D
ON B.StuAdvisorEmail = D.UseEmail;

Using a group by to group a select statement

Using a group by to group a select stament
SELECT
k.Ivalue, k.JOBDESCRIPTION ,
count( k.Ivalue) as TOTAL
FROM
(SELECT
a."ID" as Ivalue, b."JOBDESCRIPTION", rq."CURRENTSTATUS"
FROM
tblG2o_Requests a
INNER JOIN
tblG2o_JOBS b ON a."JOBPOSTID" = b."ID"
INNER JOIN
(SELECT
r.REQUESTID, ir."CURRENTSTATUS"
FROM
TBLG2O_RESULTSPOOL r
INNER JOIN
tblG2o_Requests ir ON r.RequestID = ir."ID"
WHERE
r.ShortListed = '1') rq ON rq.REQUESTID = a."ID"
WHERE
"ACTIVE" = '1'
AND "DATECOMPLETED" IS NULL
ORDER BY
"REQUESTDATE" DESC) k
GROUP BY
k.JOBDESCRIPTION
What is the question? You seem to be missing the group by clause, and you do not need double quotes around field names unless you have spaces in them, and even then, if TSQL for example, you would use [] in preference.
I had to remove an ORDER BY in the subquery, that isn't allowed unless other conditions demand it (like TOP n in TSQL)
SELECT
k.Ivalue
, k.JOBDESCRIPTION
, COUNT(k.Ivalue) AS TOTAL
FROM (
SELECT
a.ID AS Ivalue
, b.JOBDESCRIPTION
, rq.CURRENTSTATUS
FROM tblG2o_Requests a
INNER JOIN tblG2o_JOBS b
ON a.JOBPOSTID = b.ID
INNER JOIN (
SELECT
r.REQUESTID
, ir.CURRENTSTATUS
FROM TBLG2O_RESULTSPOOL r
INNER JOIN tblG2o_Requests ir
ON r.RequestID = ir.ID
WHERE r.ShortListed = '1'
) rqenter
ON rq.REQUESTID = a.ID
WHERE ACTIVE = '1'
AND DATECOMPLETED IS NULL
) k
GROUP BY
k.Ivalue
, k.JOBDESCRIPTION
Finally worked
SELECT
k.Ivalue
, l.JOBDESCRIPTION
, k.TOTAL,
k.CURRENTSTATUS
FROM (
SELECT
a.ID AS Ivalue
,b.ID as JobPostID
, rq."CURRENTSTATUS"
,COUNT(a.ID) AS TOTAL
FROM tblG2o_Requests a
INNER JOIN tblG2o_JOBS b
ON a."JOBPOSTID" = b.ID
INNER JOIN (
SELECT
r."REQUESTID"
, ir."CURRENTSTATUS"
FROM TBLG2O_RESULTSPOOL r
INNER JOIN tblG2o_Requests ir
ON r."REQUESTID" = ir.ID
WHERE r."SHORTLISTED" = 1
) rq
ON rq."REQUESTID" = a.ID
WHERE ACTIVE = '1'
AND DATECOMPLETED IS NULL
GROUP BY
a.ID ,b.ID
, rq."CURRENTSTATUS" ) k
inner join tblG2o_JOBS l on k.JobPostID =l.ID
enter code here

How to convert correlated sub query containing duplicate table to non-correlated one?

I have to convert the correlated sub-query to non-correlated sub-query cuz of performance issues .
like that :
The correlated sub-query :(So slow ) returns 4000 row
SELECT a.personid,a.name,b.conid,d.condat,e.connam
FROM main_empr a INNER JOIN coninr b
ON a.personid = b.personid AND a.calc_year = b.calc_year
INNER JOIN mainconinr c
ON b.conid = c.conid
INNER JOIN coninr d
ON a.personid = d.personid AND a.calc_year = d.calc_year
INNER JOIN mainconinr e
ON d.conid = e.conid
WHERE c.active_flag = 1 and c.endreward_flag = 1
AND d.condat = (SELECT MIN(bb.condat) FROM coninr bb WHERE bb.personid = b.personid AND bb.calc_year = b.calc_year AND ((bb.conid > 0 AND bb.conid < 4 ) OR (bb.conid IN(16,6) )) )
AND b.condat = (SELECT MAX(bb.condat) FROM coninr bb WHERE bb.personid = b.personid AND bb.calc_year = b.calc_year AND ((bb.conid > 0 AND bb.conid < 4 ) OR (bb.conid IN(16,6) )) )
AND ( 0 = ( SELECT COUNT(*) FROM servmain x WHERE x.personid = a.personid AND x.calc_year = a.calc_year )
OR b.condat > ( SELECT MAX(x.serv_date) FROM servmain x WHERE x.personid = a.personid AND x.calc_year = a.calc_year ) )
AND a.calc_year = 2018
The non-correlated query :returns about 12300 rows!!
SELECT a.personid,a.name,b.conid,d.condat,e.connam
FROM main_empr a INNER JOIN
coninr b
ON a.personid = b.personid AND a.calc_year = b.calc_year
INNER JOIN mainconinr c
ON b.conid = c.conid
INNER JOIN coninr d
ON a.personid = d.personid AND a.calc_year = d.calc_year
INNER JOIN mainconinr e ON d.conid = e.conid
INNER JOIN
(SELECT MAX(bb.condat) AS condat ,bb.personid,bb.calc_year ,bb.conid
FROM coninr bb
GROUP BY bb.personid,bb.calc_year,bb.conid
)Max_cont
ON Max_cont.personid = b.personid AND Max_cont.calc_year = b.calc_year AND Max_cont.condat = b.condat AND ((Max_cont.conid > 0 AND Max_cont.conid < 4 ) OR (Max_cont.conid IN(16,6) ))
INNER JOIN
(SELECT MIN(dd.condat) AS condat ,dd.personid,dd.calc_year,dd.conid
FROM coninr dd GROUP BY dd.personid,dd.calc_year,dd.conid
)Min_cont
ON Min_cont.personid = d.personid AND Min_cont.calc_year = d.calc_year AND Min_cont.condat = d.condat AND ((Min_cont.conid > 0 AND Min_cont.conid < 4 ) OR (Min_cont.conid IN(16,6) ))
WHERE c.active_flag = 1 and c.endreward_flag = 1
AND ( 0 = ( SELECT COUNT(*) FROM servmain x WHERE x.personid = a.personid AND x.calc_year = a.calc_year )
OR b.condat > ( SELECT MAX(x.serv_date) FROM servmain x WHERE x.personid = a.personid AND x.calc_year = a.calc_year ) )
AND a.calc_year = 2018
The problem is :
I use the coninr table twice to get the last and the first contract date in the same row .
It works fine in the first query but it was so slow because of the correlated sub-query,but in the second query it brings more than one row for the same person one of them for the first contract date and the other for the last one !!
How to fix this problem ?
This looks reasonable, but I've no way to know how it'll perform:
SELECT a.personid,a.name,b.conid,d.condat,e.connam
FROM main_empr a INNER JOIN coninr b
ON a.personid = b.personid AND a.calc_year = b.calc_year
INNER JOIN mainconinr c
ON b.conid = c.conid
INNER JOIN coninr d
ON a.personid = d.personid AND a.calc_year = d.calc_year
INNER JOIN mainconinr e
ON d.conid = e.conid
inner join
(
SELECT bb.personid, bb.calc_year, bb.conid, MIN(bb.condat) MinDate, MAX(bb.condat) MaxDate
FROM coninr bb WHERE
where (bb.conid > 0 and bb.conid < 4) or (bb.conid in (6, 16))
group by bb.personid, bb.calc_year, bb.conid
) zz on d.concat = zz.MinDate and b.condat = zz.MaxDate and b.personid = zz.personid and b.calc_year = zz.calc_year
left outer join
(
select s.personid, s.calc_year, max(s.serv_date) MaxServDate
from servmain s
group by s.personid, s.calc_year
) s on a.personid = s.personid and a.calc_year = s.calc_year
WHERE c.active_flag = 1 and c.endreward_flag = 1
and (s.MaxServDate is null or b.condat ? s.MaxServDate
AND a.calc_year = 2018
You don't need two queries for table coninr, you can get min and max in the same query with the group by. Also, for ServMain, doing a left outer join and putting in the where that either it's null (equivalent to count(*) = 0) or is less than b.condat takes care of that.

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.