Sum a union query - sql

I'm using Microsoft SQL Svr Mgmt Studio 2008. I don't have access to create a temporary table (company restricts ability to create or modify tables) or I would use that to solve this problem.
I have successfully used a union query to combine the results of three select queries. Now I am trying to sum the results of the union.
When I execute the query below I receive:
Incorrect syntax near the keyword 'GROUP'
And then when I remove the group by I get:
Incorrect syntax near ')'
Here's my query so far:
Select Period, PCC, SUM(BasicHits), SUM(FareHits), SUM(SearchHits)
From (
SELECT AAAPeriod AS Period,
AAAFromPCC AS PCC,
- SUM(AAABasic) AS BasicHits,
- SUM(AAAFare) AS FareHits,
- SUM(AAASearch) AS SearchHits
FROM HitsAaa
HAVING (AAAPeriod = N'2010-10')
UNION ALL
SELECT AAAPeriod,
AAAtoPCC,
SUM(AAABasic),
SUM(AAAFare),
SUM(AAASearch)
FROM HitsAaa
HAVING (AAAPeriod = N'2010-10')
UNION ALL
SELECT AgtPeriod,
AgtPcc,
SUM(AgtBasic),
SUM(AgtFare),
SUM(AgtSearch)
FROM HitsAgent
HAVING (AgtPeriod = N'2010-10')
)GROUP BY Period, PCC
I haven't been able to find a solution to this on any of the previous questions.

You need to alias your derived table, you must also use a group by with a having clause.
SELECT
q1.Period,
q1.PCC,
SUM(q1.BasicHits),
SUM(q1.FareHits),
SUM(q1.SearchHits)
FROM (SELECT
AAAPeriod AS Period,
AAAFromPCC AS PCC,
- SUM(AAABasic) AS BasicHits,
- SUM(AAAFare) AS FareHits,
- SUM(AAASearch) AS SearchHits
FROM HitsAaa
GROUP BY
AAAPeriod,
AAAFromPCC
HAVING (AAAPeriod = N'2010-10')
UNION ALL
SELECT
AAAPeriod AS Period,
AAAtoPCC AS PCC,
SUM(AAABasic) AS BasicHits,
SUM(AAAFare) AS FareHits,
SUM(AAASearch) AS SearchHits
FROM HitsAaa
GROUP BY
AAAPeriod,
AAAtoPCC
HAVING (AAAPeriod = N'2010-10')
UNION ALL
SELECT
AgtPeriod AS Period,
AgtPcc AS PCC,
SUM(AgtBasic) AS BasicHits,
SUM(AgtFare) AS FareHits,
SUM(AgtSearch) AS SearchHits
FROM HitsAgent
GROUP BY
AgtPeriod,
AgtPCC
HAVING (AgtPeriod = N'2010-10')) q1
GROUP BY
q1.Period,
q1.PCC

SQL Server requires that you define a table alias for a derived table/inline view:
SELECT x.period, x.pcc, SUM(x.BasicHits), SUM(x.FareHits), SUM(x.SearchHits)
FROM (SELECT AAAPeriod AS Period,
AAAFromPCC AS PCC,
- SUM(AAABasic) AS BasicHits,
- SUM(AAAFare) AS FareHits,
- SUM(AAASearch) AS SearchHits
FROM HitsAaa
WHERE AAAPeriod = N'2010-10'
GROUP BY aaaperiod, aaafrompcc
UNION ALL
SELECT AAAPeriod,
AAAtoPCC,
SUM(AAABasic),
SUM(AAAFare),
SUM(AAASearch)
FROM HitsAaa
WHERE AAAPeriod = N'2010-10'
GROUP BY aaaperiod, aaafrompcc
UNION ALL
SELECT AgtPeriod,
AgtPcc,
SUM(AgtBasic),
SUM(AgtFare),
SUM(AgtSearch)
FROM HitsAgent
WHERE AgtPeriod = N'2010-10'
GROUP BY agtperiod, agtpcc) AS x
GROUP BY x.period, x.pcc

I don't have access to create a
temporary table (company restricts
ability to create or modify tables) or
I would use that to solve this
problem.
Instead of a temporary table, try using a table variable:
declare #t table (id int primary key, col1 varchar(50))
insert #t (col1) values ('hello table variable')
select * from #t
A table variable can do most of the things a temporary table can.
Like Martin's (now deleted) answer suggests, consider giving the subquery an alias, like:
select ... list of columns ...
from (
... subquery ...
) as SubQueryAlias
group by
col1
And in your subquery, the having should probably be a where:
...
FROM HitsAaa
WHERE (AAAPeriod = N'2010-10')
...

Change your first line to
Select T.Period, T.PCC, SUM(T.BasicHits), SUM(T.FareHits), SUM(T.SearchHits)
and the last line to
) T GROUP BY T.Period, T.PCC
You need to define a table alias (in this case T) for inner tables
Also, you need to GROUP BY the inner queries

select R."Artigo", R."Dscription" as "Descricao",
R."Codigo", R."Cliente",
R."ItmsGrpCod", Sum(R."Qtd/Kg") as "Qtd/Kg", Sum(R."Valor") as "Valor",
Sum(R."Valor")/Sum(R."Qtd/Kg") as "PMVL"
from (
select T1."ItemCode" as "Artigo", T1."Dscription",
T0."CardCode" as "Codigo", T0."CardName" as "Cliente",
T3."ItmsGrpCod", Sum(T1."Quantity")-1 as "Qtd/Kg",
Sum(T1."LineTotal")-1 as "Valor",
( Sum(T1."LineTotal") / Sum(T1."Quantity") ) as "PMVL"
from
ORIN T0 INNER JOIN RIN1 T1 ON T0."DocEntry" = T1."DocEntry"
RIGHT JOIN OITM T3 ON T1."ItemCode" = T3."ItemCode"
LEFT JOIN IBT1 T2 ON T0."DocEntry" = T2."BaseEntry" AND T1."ItemCode"=T2."ItemCode" and T2."BaseLinNum"=T1."LineNum"
where T0."DocDate" >= ('2021-03-19') and T0."DocDate" <= ('2021-03-19')
and T3."ItmsGrpCod" like '___'
and T0.CANCELED = 'N'
group by T1."ItemCode", T1."Dscription", T0."CardCode", T0."CardName", T3."ItmsGrpCod"
union
-- facturas
select T1."ItemCode" as "Artigo", T1."Dscription",
T0."CardCode" as "Codigo", T0."CardName" as "Cliente",
T3."ItmsGrpCod", Sum(T1."Quantity") as "Qtd/Kg", Sum(T1."LineTotal") as "Valor", ( Sum(T1."LineTotal") / Sum(T1."Quantity") ) as "PMVL"
from
OINV T0 INNER JOIN INV1 T1 ON T0."DocEntry" = T1."DocEntry"
-- LEFT JOIN OITM T3 ON T1."ItemCode" = T3."CardCode"
left JOIN OITM T3 ON T1."ItemCode" = T3."ItemCode"
-- INNER JOIN OITM T3 ON T3."ItemCode" = T3."CardCode"
LEFT JOIN IBT1 T2 ON T0."DocEntry" = T2."BaseEntry" AND T1."ItemCode"=T2."ItemCode" and T2."BaseLinNum"=t1."LineNum"
where T0."DocDate" >= ('2021-03-19') and T0."DocDate" <= ('2021-03-19')
and T3."ItmsGrpCod" like '___'
group by T1."ItemCode", T1."Dscription", T0."CardCode", T0."CardName",T3."ItmsGrpCod"
) as R
group by R."Artigo", R."Dscription", R."Codigo", R."Cliente",R."ItmsGrpCod"

Related

SQL make query from two queries

I have two tables in a SQL database and I have made two queries for getting the data, but now I need to merge them in one query for having a single table.
First query is:
SELECT
Costruttore.longname AS Costruttore,
Parti.partnr, Parti.ordernr,
Parti.description1, Parti.packagingquantity, Parti.quantityunit
FROM
tblPart AS Parti
LEFT OUTER JOIN
tblAddress AS Costruttore ON Parti.manufacturer = Costruttore.shortname
LEFT OUTER JOIN
tblAddress AS Fornitore ON Parti.supplier = Fornitore.shortname
WHERE
(Parti.id = 12757)
The second query is:
SELECT *
FROM
(SELECT Id, identname, val
FROM tblUserFreeProperty) AS SOURCETABLE
PIVOT
(MAX(val)
FOR identname IN ([DSR_Mag.Gestito],
[DSR_Mag.StatoProdotto],
[DSR_Mag.Qta_Cassetto],
[DSR_Mag.Qta_Min],
[DSR_Mag.UbicazioneMag],
[DSR_Mag.UbicazioneScaf],
[DSR_Mag.UbicazionePiano],
[DSR_Mag.UbicazioneCass])) AS PIVOTTABLE
WHERE
id = 12757
I have tried with this query:
SELECT *
FROM (SELECT Id, identname, val FROM tblUserFreeProperty) AS SOURCETABLE
PIVOT (MAX(val)
FOR identname In ( [DSR_Mag.Gestito],
[DSR_Mag.StatoProdotto],
[DSR_Mag.Qta_Cassetto],
[DSR_Mag.Qta_Min],
[DSR_Mag.UbicazioneMag],
[DSR_Mag.UbicazioneScaf],
[DSR_Mag.UbicazionePiano],
[DSR_Mag.UbicazioneCass])
) AS PIVOTTABLE
inner JOIN tblpart as Parti ON PIVOTTABLE.id=Parti.id
where PIVOTTABLE.[DSR_Mag.Qta_Cassetto]>0
This works, but I can see all the properies in tblPart. If I add some properties in the main select (like the first query: Parti.partnr, Parti.ordernr,Parti.description1, Parti.packagingquantity, Parti.quantityunit I lose the results in the subquery)
I need to make a query with a subquery with the same condition Where Parti.id=PIVOTTABLE.id
Is there a way to do this?
Solved...the final query is:
SELECT Parti.partnr, Parti.ordernr, Costruttore.longname AS Costruttore,
Descrizione= IIF(CharIndex(';', description1)-1 > 0 ,(SUBSTRING(description1, (charIndex(';it_IT#', description1)+7),(charIndex(';', description1, (charIndex(';it_IT#', description1)+7))- (charIndex(';it_IT#', description1)+7)))), Null ),
Parti.packagingquantity,
'UM'= IIF(CharIndex(';', quantityunit)-1 > 0 ,( SubString(Left(quantityunit,CharIndex(';', quantityunit)-1), CharIndex('#', quantityunit)+1,LEN(quantityunit))), Null),
'Gestito'= Trim('?_#;' FROM PIVOTTABLE.[DSR_Mag.Gestito]),
'Stato Prodotto'= Trim('?_#;' FROM PIVOTTABLE.[DSR_Mag.StatoProdotto]),
'Giacenza'= Trim('?_#;' FROM PIVOTTABLE.[DSR_Mag.Qta_Cassetto]),
'Quantità minima'= Trim('?_#;' FROM PIVOTTABLE.[DSR_Mag.Qta_Min]),
'Ubic.Magazzino'= Trim('?_#;' FROM PIVOTTABLE.[DSR_Mag.UbicazioneMag]),
'Ubic.Scaffale'= Trim('?_#;' FROM PIVOTTABLE.[DSR_Mag.UbicazioneScaf]),
'Ubic.Piano'= Trim('?_#;' FROM PIVOTTABLE.[DSR_Mag.UbicazionePiano]),
'Ubic.Cassetto'= Trim('?_#;' FROM PIVOTTABLE.[DSR_Mag.UbicazioneCass])
FROM (SELECT Id, identname, val FROM tblUserFreeProperty) AS SOURCETABLE
PIVOT (MAX(val)
FOR identname In ( [DSR_Mag.Gestito],
[DSR_Mag.StatoProdotto],
[DSR_Mag.Qta_Cassetto],
[DSR_Mag.Qta_Min],
[DSR_Mag.UbicazioneMag],
[DSR_Mag.UbicazioneScaf],
[DSR_Mag.UbicazionePiano],
[DSR_Mag.UbicazioneCass])
) AS PIVOTTABLE INNER JOIN tblpart as Parti ON PIVOTTABLE.id=Parti.id
LEFT OUTER JOIN tblAddress AS Costruttore ON Parti.manufacturer = Costruttore.shortname
LEFT OUTER JOIN tblAddress AS Fornitore ON Parti.supplier = Fornitore.shortname
WHERE cast(substring(PIVOTTABLE.[DSR_Mag.Qta_Cassetto], CharIndex('#', PIVOTTABLE.[DSR_Mag.Qta_Cassetto])+1,len(PIVOTTABLE.[DSR_Mag.Qta_Cassetto])-7) as int)>0

How to use Order By and With clause

I am using following SQL query to fetch set of records.
;WITH SFPIPELINE AS (
SELECT
PIPELINE_STRING,
PACKET_NUMBER,
PIPELINE_NUMBER
FROM
[RTMASTER].[DBO].[SF_PIPELINE]
WHERE
PIPELINE_STRING IN (
'SOLUTION_TEST',
'2018.01_SVC_SANDBOX',
'2018.01_SVC_ENG'
)
AND PACKET_NUMBER IN (98, 1090, 1092)
),
PROJ_INST_PIPELINE AS (
SELECT
DISTINCT PIP.PROJECT_INSTANCE_PIPELINE_ID,
PIP.PROJECT_INSTANCE_ID,
PIP.PACKET_NUMBER,
PIP.PROJECT_NUMBER,
PIP.SOURCE_SET_INSTANCE,
SFP.PIPELINE_STRING
FROM
PROJECT_INSTANCE_PIPELINE PIP
INNER JOIN SFPIPELINE SFP ON PIP.PACKET_NUMBER = SFP.PACKET_NUMBER
AND PIP.PIPELINE_NUMBER = SFP.PIPELINE_NUMBER
AND PIP.ACTIVE = 1
AND PIP.PROJECT_INSTANCE_PIPELINE_ID >= 20481038
),
PROJ_INST_BASE AS (
SELECT
PIP.PROJECT_INSTANCE_PIPELINE_ID,
PIP.PROJECT_NUMBER,
PIP.PACKET_NUMBER,
PIP.PIPELINE_STRING,
PIP.SOURCE_SET_INSTANCE,
PIP.PROJECT_INSTANCE_ID,
PIB.ORIGINAL_PROMOTER,
PIB.DEV_INSTANCE,
PROJECT_TYPE_NUMBER,
PIB.SUBVERSION_PROJECT_REVISION,
PIB.SUBVERSION _PROJECT_URL,
PIB.Front_End,
PIB.Back_End
FROM
PROJECT_INSTANCE_BASE PIB
INNER JOIN PROJ_INST_PIPELINE PIP ON PIB.PROJECT_INSTANCE_ID = PIP.PROJECT_INSTANCE_ID
AND PIP.PROJECT_NUMBER = PIB.PROJECT_NUMBER
AND PIB.PROJECT_TYPE_NUMBER IN (5, 105, 106)
),
SF_PROJ AS (
SELECT
PJTINST.PROJECT_INSTANCE_PIPELINE_ID,
PJTINST.PROJECT_INSTANCE_ID,
PJTINST.PROJECT_NUMBER,
PJTINST.PIPELINE_STRING,
PJTINST.ORIGINAL_PROMOTER,
PJTINST.SOURCE_SET_INSTANCE,
PJTINST.PROJECT_TYPE_NUMBER,
PJTINST.PACKET_NUMBER,
SFP.PROJECT_NAME,
PJTINST.SUBVERSION_PROJECT_REVISION,
PJTINST.SUBVERSION_PROJECT_URL,
PJTINST.Front_End,
PJTINST.Back_End
FROM
DBO.SF_PROJECT SFP
INNER JOIN PROJ_INST_BASE PJTINST ON SFP.PROJECT_NUMBER = PJTINST.PROJECT_NUMBER
),
USER_DETAIL AS (
SELECT
SFP.PROJECT_NAME,
SFP.PROJECT_NUMBER,
SFP.PROJECT_TYPE_NUMBER,
SFP.SOURCE_SET_INSTANCE,
SFP.PACKET_NUMBER,
SFP.PIPELINE_STRING,
SFP.SUBVERSION_PROJECT_REVISION,
SFP.SUBVERSION_PROJECT_URL,
SFP.PROJECT_INSTANCE_PIPELINE_ID,
SFP.PROJECT_INSTANCE_ID,
AIAA.EMAIL_ADDRESS,
SFP.Front_End,
SFP.Back_End
FROM
SF_ASSOCIATE_INFO_ALL_ASSOCIATES AIAA
INNER JOIN SF_PROJ SFP ON AIAA.OPER_ID = SFP.ORIGINAL_PROMOTER
),
FINAL AS (
SELECT
UD.PROJECT_NAME,
FP.Feature_Number,
UD.PROJECT_NUMBER,
UD.PROJECT_TYPE_NUMBER,
UD.SOURCE_SET_INSTANCE,
UD.PACKET_NUMBER,
UD.PIPELINE_STRING,
UD.SUBVERSION_PROJECT_REVISION,
UD.SUBVERSION_PROJECT_URL,
UD.PROJECT_INSTANCE_PIPELINE_ID,
UD.PROJECT_INSTANCE_ID,
UD.EMAIL_ADDRESS,
UD.Front_End,
UD.Back_End
FROM
[RTMaster].[dbo].[Feature_Projects_History] FP
INNER JOIN USER_DETAIL UD ON FP.Project_Instance_Pipeline_ID = UD.PROJECT_INSTANCE_PIPELINE_ID
)
SELECT
*
FROM
FINAL
Query is working fine only thing is the records are not sorted.
I want to use order by on PROJECT_INSTANCE_PIPELINE_ID so that all the rows are sorted. When I use ORDER BY clause seeing following error.
Error:
The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP, OFFSET or FOR XML is also specified.
Not sure how to use Order By and With Clause together.
Any thoughts!
try like below i just used PROJECT_NAME in order by
WITH SFPIPELINE AS
(SELECT PIPELINE_STRING, PACKET_NUMBER, PIPELINE_NUMBER FROM [RTMASTER].[DBO].[SF_PIPELINE]
WHERE PIPELINE_STRING IN ( 'SOLUTION_TEST', '2018.01_SVC_SANDBOX', '2018.01_SVC_ENG')
AND PACKET_NUMBER IN (98, 1090, 1092)),
PROJ_INST_PIPELINE AS
(SELECT DISTINCT PIP.PROJECT_INSTANCE_PIPELINE_ID, PIP.PROJECT_INSTANCE_ID, PIP.PACKET_NUMBER, PIP.PROJECT_NUMBER, PIP.SOURCE_SET_INSTANCE, SFP.PIPELINE_STRING FROM PROJECT_INSTANCE_PIPELINE PIP
INNER JOIN SFPIPELINE SFP ON PIP.PACKET_NUMBER = SFP.PACKET_NUMBER AND PIP.PIPELINE_NUMBER = SFP.PIPELINE_NUMBER AND PIP.ACTIVE = 1
AND PIP.PROJECT_INSTANCE_PIPELINE_ID >= 20481038),
PROJ_INST_BASE AS
(SELECT PIP.PROJECT_INSTANCE_PIPELINE_ID, PIP.PROJECT_NUMBER, PIP.PACKET_NUMBER, PIP.PIPELINE_STRING, PIP.SOURCE_SET_INSTANCE, PIP.PROJECT_INSTANCE_ID, PIB.ORIGINAL_PROMOTER, PIB.DEV_INSTANCE,PROJECT_TYPE_NUMBER, PIB.SUBVERSION_PROJECT_REVISION, PIB.SUBVERSION_PROJECT_URL,
PIB.Front_End, PIB.Back_End FROM PROJECT_INSTANCE_BASE PIB INNER JOIN PROJ_INST_PIPELINE PIP ON PIB.PROJECT_INSTANCE_ID = PIP.PROJECT_INSTANCE_ID AND PIP.PROJECT_NUMBER= PIB.PROJECT_NUMBER AND PIB.PROJECT_TYPE_NUMBER IN (5,105, 106)),
SF_PROJ AS
(SELECT PJTINST.PROJECT_INSTANCE_PIPELINE_ID, PJTINST.PROJECT_INSTANCE_ID, PJTINST.PROJECT_NUMBER, PJTINST.PIPELINE_STRING, PJTINST.ORIGINAL_PROMOTER, PJTINST.SOURCE_SET_INSTANCE, PJTINST.PROJECT_TYPE_NUMBER, PJTINST.PACKET_NUMBER, SFP.PROJECT_NAME,
PJTINST.SUBVERSION_PROJECT_REVISION, PJTINST.SUBVERSION_PROJECT_URL, PJTINST.Front_End, PJTINST.Back_End FROM DBO.SF_PROJECT SFP INNER JOIN PROJ_INST_BASE PJTINST ON SFP.PROJECT_NUMBER = PJTINST.PROJECT_NUMBER),
USER_DETAIL AS
(SELECT SFP.PROJECT_NAME, SFP.PROJECT_NUMBER, SFP.PROJECT_TYPE_NUMBER, SFP.SOURCE_SET_INSTANCE, SFP.PACKET_NUMBER, SFP.PIPELINE_STRING, SFP.SUBVERSION_PROJECT_REVISION, SFP.SUBVERSION_PROJECT_URL, SFP.PROJECT_INSTANCE_PIPELINE_ID, SFP.PROJECT_INSTANCE_ID, AIAA.EMAIL_ADDRESS, SFP.Front_End, SFP.Back_End
FROM SF_ASSOCIATE_INFO_ALL_ASSOCIATES AIAA INNER JOIN SF_PROJ SFP ON AIAA.OPER_ID = SFP.ORIGINAL_PROMOTER),
FINAL AS
(SELECT UD.PROJECT_NAME, FP.Feature_Number, UD.PROJECT_NUMBER, UD.PROJECT_TYPE_NUMBER, UD.SOURCE_SET_INSTANCE, UD.PACKET_NUMBER, UD.PIPELINE_STRING, UD.SUBVERSION_PROJECT_REVISION, UD.SUBVERSION_PROJECT_URL,
UD.PROJECT_INSTANCE_PIPELINE_ID, UD.PROJECT_INSTANCE_ID, UD.EMAIL_ADDRESS, UD.Front_End, UD.Back_End FROM [RTMaster].[dbo].[Feature_Projects_History] FP
INNER JOIN USER_DETAIL UD ON FP.Project_Instance_Pipeline_ID = UD.PROJECT_INSTANCE_PIPELINE_ID)
SELECT * FROM FINAL order by PROJECT_NAME -- use here others column name as you need

SQL Select multiple joins and MAX(field) result

I'm using IBM Cognos to create a report which allows for fairly standard SQL. I am ultimately trying to take data from 2 tables and compare them to each other to ensure they match. Billing_Term, Bill_Period and Contract_Term_Amount all need to match when comparing a given Contract_Number, Contract_Item and Stream_Type between t1 and t3 but only for the MAX Seq_No from t3.
I tried a simple MAX() on Seq_No but that didn't work so I'm looking for help in limiting the results to the MAX Seq_No for the associated query results.
SELECT
t1.Contract_Number,
t1.Contract_Item,
t1.Stream_Type,
t1.Billing_Term,
t1.Bill_Period,
t1.Contract_Term_Amount,
t2.Reference_Document,
t3.Billing_Term,
t3.Bill_Period,
t3.Contract_Term_Amount,
t3.Seq_No
FROM
LeasingStreamData t1
INNER JOIN ContractsData t2 ON t1.Contract_Number = t2.Sales_Document
LEFT JOIN LeasingStreamData t3 ON t2.Reference_Document = t3.Contract_Number AND
t1.Contract_Item = t3.Contract_Item AND
t1.Stream_Type = t3.Stream_Type
WHERE
t1.Contract_Number IN ([some list of contracts])
GROUP BY
t1.Contract_Number,
t1.Contract_Item,
t1.Stream_Type,
t1.Billing_Term,
t1.Bill_Period,
t1.Contract_Term_Amount,
t2.Reference_Document,
t3.Billing_Term,
t3.Bill_Period,
t3.Contract_Term_Amount,
t3.Seq_No
I hope this is enough to get some much needed help, many thanks for any assistance you can provide!
If I understand you requirement, I think you want to create queries and join them in a way that will look like this SQL:
SELECT
t1.Contract_Number
, t1.Contract_Item
, t1.Stream_Type
, t1.Billing_Term
, t1.Bill_Period
, t1.Contract_Term_Amount
, t2.Reference_Document
, t3.Billing_Term
, t3.Bill_Period
, t3.Contract_Term_Amount
, t3.Seq_No
FROM (
SELECT Contract_Number
, Contract_Item
, Stream_Type
, Billing_Term
, Bill_Period
, Contract_Term_Amount
FROM LeasingStreamData
WHERE Contract_Number in ([some list of contracts])
) t1
INNER JOIN (
SELECT Sales_Document
, Reference_Document
FROM ContractsData
WHERE Sales_Document in ([some list of contracts])
) t2 ON t1.Contract_Number = t2.Sales_Document
INNER JOIN LeasingStreamData t3 ON t2.Reference_Document = t3.Contract_Number
AND t1.Contract_Item = t3.Contract_Item
AND t1.Stream_Type = t3.Stream_Type
INNER JOIN (
select max(Seq_No) as Seq_No
, Contract_Number
, Contract_Item
, Stream_Type
from LeasingStreamData lsd
group by Contract_Number
, Contract_Item
, Stream_Type
) maxseq on maxseq.Contract_Number = t3.Contract_Number
and maxseq.Contract Item = t3.Contract_Item
and maxseq.Stream_Type = t3.Stream_Type
and maxseq.Seq_No = t3.Seq_No
WHERE t1.Billing_Term <> t3.Billing_Term
and t1.Bill_Period <> t3.Bill_Period
and t1.Contract_Term_Amount <> t3.Contract_Term_Amount
GROUP BY
t1.Contract_Number
, t1.Contract_Item
, t1.Stream_Type
, t1.Billing_Term
, t1.Bill_Period
, t1.Contract_Term_Amount
, t2.Reference_Document
, t3.Billing_Term
, t3.Bill_Period
, t3.Contract_Term_Amount
, t3.Seq_No
I think this will filter to only the max Seq_No for t3 and return only the records that you care about (the ones that don't match).
Try this:
SELECT t1.Contract_Number
,t1.Contract_Item
,t1.Stream_Type
,t1.Billing_Term
,t1.Bill_Period
,t1.Contract_Term_Amount
,t2.Reference_Document
,t3.Billing_Term
,t3.Bill_Period
,t3.Contract_Term_Amount
,t3.Seq_No
FROM LeasingStreamData t1
INNER JOIN ContractsData t2 ON t1.Contract_Number = t2.Sales_Document
LEFT JOIN (
SELECT Contract_Number
,Contract_Item
,Stream_type
,MAX(Seq_No) AS "Seq_No"
FROM LeasingStreamData
GROUP BY Contract_Number
,Contract_Item
,Stream_Type
) t3 ON t2.Reference_Document = t3.Contract_Number
AND t1.Contract_Item = t3.Contract_Item
AND t1.Stream_Type = t3.Stream_Type
WHERE t1.Contract_Number IN ([some list of contracts])
Since the rollup for the aggregate function (MAX) relies on the group by to determine context, you have to isolate it via a subquery to get the max before joining to the rest of the tables.
Also, since you are preaggregating the max sequence number, you no longer need a group by in the main query.

How to Join two select statements

I have four tables. I wrote 2 queries independently and those are working. But what I want to do is join those two queries and generate one result.
Here is my code
Query #1
SELECT
pm.DATE
,pm.customer
,pm.gp_no AS Gatepass_Num
,pf.style
,pf.color
,pf.batch_no
,COUNT(pf.roll_no) AS Roll_QTY
,SUM(pf.meter) AS QTY
FROM
(packinglists_fabrics_items pf
,packinglists_main pm
WHERE
pf.p_id = pm.id
[AND pm.date between {DateR,RANGE1} and {DateR,RANGE2}]
[AND pm.customer_id = "{factory,false}"]
GROUP BY
pm.DATE, pm.gp_no, pf.style, pf.color, pf.batch_no)
Query #2:
SELECT
lo.DATE
,lo.customer_name
,flo.style
,flo.color
,flo.batch_no
,COUNT(flo.rowno) AS Roll_QTY
,SUM(flo.meter) AS QTY_Meter
FROM
loadinglists_fabrics_items flo, loadinglists lo
WHERE
flo.p_id = lo.id
[AND lo.date between {DateR,RANGE1} and {DateR,RANGE2}]
[AND lo.customer_id = "{factory,false}"]
GROUP BY
lo.DATE, flo.style, flo.color, flo.batch_no
batch_no is unique for loadinglists_fabrics_items table and packinglists_fabrics_items table
Result of query 1
Result of query 2
Expected output
Try like this, I assume that you are using SQL Server
SELECT A.*
,B.*
FROM (
SELECT pm.DATE
,pm.customer
,pm.gp_no AS Gatepass_Num
,pf.style
,pf.color
,pf.batch_no
,COUNT(pf.roll_no) AS Roll_QTY
,SUM(pf.meter) AS QTY
FROM packinglists_fabrics_items pf
,packinglists_main pm
WHERE pf.p_id = pm.id
AND pm.DATE BETWEEN {DateR
,RANGE1}
AND {DateR
,RANGE2}
AND pm.customer_id = "{factory,false}"
GROUP BY pm.DATE
,pm.gp_no
,pf.style
,pf.color
,pf.batch_no
) A
INNER JOIN (
SELECT lo.DATE
,lo.customer_name
,flo.style
,flo.color
,flo.batch_no
,COUNT(flo.rowno) AS Roll_QTY
,SUM(flo.meter) AS QTY_Meter
FROM loadinglists_fabrics_items flo
,loadinglists lo
WHERE flo.p_id = lo.id
AND lo.DATE BETWEEN {DateR
,RANGE1}
AND {DateR
,RANGE2}
AND lo.customer_id = "{factory,false}"
GROUP BY lo.DATE
,flo.style
,flo.color
,flo.batch_no
) B ON A.batch_no = B.batch_no

another union all selecting all the rows that have not already been selected

Right now i have 2 select statements that are joined by a union what i was hopping to do was maybe name the first query like query1 and the second one query2 and then in my third query do a where bookno not in query1 or query2.
SELECT distinct t0.BOOKNO, t0.PaxName, t0.Locator, t0.FDATE7,
t0.BOARD, t0.ALIGHT, t0.AIRLINE, t0.FNUMBR, t0.DEP,
t0.ARR, t0.TOUR, t0.ROUTE,
t1.tour, t1.route, t1.sfrom , t1.sto,t1.seq,t0.seq, 'yes'
FROM
( SELECT TOP (100) PERCENT test.dbo.BNAMES.BOOKNO, RTRIM(test.dbo.BNAMES.SRNAME) + '/' + RTRIM(test.dbo.BNAMES.FIRST) + RTRIM(test.dbo.BNAMES.TITLE)
AS PaxName, test.dbo.PNRS.PNR AS Locator, test.dbo.PNRSECTORS.FDATE7, test.dbo.PNRSECTORS.BOARD, test.dbo.PNRSECTORS.ALIGHT,
test.dbo.PNRSECTORS.AIRLINE, test.dbo.PNRSECTORS.FNUMBR, test.dbo.PNRSECTORS.DEP, test.dbo.PNRSECTORS.ARR, test.dbo.BOOKINGS.TOUR,
test.dbo.BOOKINGS.ROUTE, test.dbo.BSTAGES.SEQ,(test.dbo.PNRSECTORS.BOARD + test.dbo.PNRSECTORS.ALIGHT) as both
FROM test.dbo.BOOKINGS LEFT OUTER JOIN
test.dbo.BNAMES ON test.dbo.BOOKINGS.BOOKNO = test.dbo.BNAMES.BOOKNO LEFT OUTER JOIN
test.dbo.BSTAGES ON test.dbo.BNAMES.BOOKNO = test.dbo.BSTAGES.BOOKNO LEFT OUTER JOIN
test.dbo.PNRSECTORS ON test.dbo.BSTAGES.SCODE = test.dbo.PNRSECTORS.SKEY LEFT OUTER JOIN
test.dbo.PNRS ON test.dbo.PNRSECTORS.PNRKEY = test.dbo.PNRS.PNRKEY
WHERE (test.dbo.BSTAGES.STYPE = 3)
ORDER BY test.dbo.BOOKINGS.BOOKNO, test.dbo.BNAMES.SEQ, locator
) t0
INNER JOIN ( SELECT TOUR, ROUTE, OFFSET, SEQ, SCODE, SFROM, STO, (SFROM + STO) AS BOTH
FROM test.dbo.TSTAGES
) t1 ON t1.tour = t0.tour and t1.route = t0.route and (t0.both = t1.both)
union all
SELECT distinct t0.BOOKNO, t0.PaxName, t0.Locator, t0.FDATE7,
t0.BOARD, t0.ALIGHT, t0.AIRLINE, t0.FNUMBR, t0.DEP,
t0.ARR, t0.TOUR, t0.ROUTE,
t1.tour, t1.route, t1.sfrom , t1.sto,t1.seq,t0.seq,'YES'
FROM
( SELECT TOP (100) PERCENT test.dbo.BNAMES.BOOKNO, RTRIM(test.dbo.BNAMES.SRNAME) + '/' + RTRIM(test.dbo.BNAMES.FIRST) + RTRIM(test.dbo.BNAMES.TITLE)
AS PaxName, test.dbo.PNRS.PNR AS Locator, test.dbo.PNRSECTORS.FDATE7, test.dbo.PNRSECTORS.BOARD, test.dbo.PNRSECTORS.ALIGHT,
test.dbo.PNRSECTORS.AIRLINE, test.dbo.PNRSECTORS.FNUMBR, test.dbo.PNRSECTORS.DEP, test.dbo.PNRSECTORS.ARR, test.dbo.BOOKINGS.TOUR,
test.dbo.BOOKINGS.ROUTE, test.dbo.BSTAGES.SEQ,(test.dbo.PNRSECTORS.BOARD + test.dbo.PNRSECTORS.ALIGHT) as both
FROM test.dbo.BOOKINGS LEFT OUTER JOIN
test.dbo.BNAMES ON test.dbo.BOOKINGS.BOOKNO = test.dbo.BNAMES.BOOKNO LEFT OUTER JOIN
test.dbo.BSTAGES ON test.dbo.BNAMES.BOOKNO = test.dbo.BSTAGES.BOOKNO LEFT OUTER JOIN
test.dbo.PNRSECTORS ON test.dbo.BSTAGES.SCODE = test.dbo.PNRSECTORS.SKEY LEFT OUTER JOIN
test.dbo.PNRS ON test.dbo.PNRSECTORS.PNRKEY = test.dbo.PNRS.PNRKEY
WHERE (test.dbo.BSTAGES.STYPE = 1)
ORDER BY test.dbo.BOOKINGS.BOOKNO, test.dbo.BNAMES.SEQ, locator
) t0
INNER JOIN ( SELECT TOUR, ROUTE, OFFSET, SEQ, SCODE, SFROM, STO, (SFROM + STO) AS BOTH
FROM test.dbo.TSTAGES
) t1 ON t1.tour = t0.tour and t1.route = t0.route and t1.seq = t0.seq and (t0.both = t1.both)
order by bookno
END
How about using WITH? You can declare you queries, join them with UNION and them search for the ones not there.
Take a look here: Multiple Select Statements using SQL Server 2005 "WITH" Statement . It should help you get started.
By using WITH statement, you will isolate logic of your queries, making your overall query more understandable.
just wrap your logic around what you wrote:
select bookno
where key not in (
your big select statement...
)