INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Jobs

2 CTE in one select

2 CTE in one select

(OP)
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')
)


RE: 2 CTE in one select

You can do two CTEs in one

CODE --> T-SQL

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.

Red Flag This Post

Please let us know here why this post is inappropriate. Reasons such as off-topic, duplicates, flames, illegal, vulgar, or students posting their homework.

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members!

Resources

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close