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