Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

2 CTE in one select

Status
Not open for further replies.

codrutza

Technical User
Mar 31, 2002
357
IE
Please help on writing this.

I have to combine in one select 2 CTEs: one which count the containers for a job, and one with sum sales for a job.
1.
;WIH Cont_CTE AS
(
SELECT CJNo
, COUNT(1) AS ContCount
FROM Cons
GROUP BY CJNo
)
2.
;WIH Sales_CTE AS
(
SELECT
J.JNo,
sum(H.Amount*H. Sign) as SumSales
from J
INNER JOIN H
ON substring(H.InvNr,2,7)=J.JNo
and substring(H.InvNr,1,1)='J'
and substring(H.InvNr,9,2)>='/1'
and substring(H.InvNr,9,2)<='/99'
and H. key='ac'
..

GROUP BY J.JNo
)

1 and 2 in:

SELECT
J.JNo ,
Custs.Code CCusCode,
Custs_2_At.Code C2AgCode,
J.Date,
Custs_1_Sen.Name C1SenName,
J.SRef,
..
J.Cer,
J.JT,
J.Via,
Cont_CTE.CountCont,
Sales_CTE.SumSales

FROM
(((Custs INNER JOIN J ON Custs.CustNo=J.CustNo)
LEFT OUTER JOIN Custs Custs_2_At ON J.AtNo=Custs_2_At.CustNo)
INNER JOIN Custs Custs_1_Sen ON J.SenNo=Custs_1_Sen.CustNo)

LEFT OUTER JOIN Cont_CTE
ON Cont_CTE.CJNo=J.JNo)

LEFT OUTER JOIN Sales_CTE
ON Sales_CTE.CJNo=J.JNo

WHERE
Custs.Code='CL’
AND
(
(J.CC='SL' AND J.JT='Imp')
or
J.CC in ('L','K')
)


 
You can do two CTEs in one

Code:
WITH someCTE(
ctequery1
),
anotherCTE(
ctequery2
)
Select From someCTE Inner Join anotherCTE ON ...

So what is your problem? You seem to think you can only do one CTE at a time, are you? That's not the case.

Bye, Olaf.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top