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
Related
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
I have a sql command like this
select mainPOID.EstAPDate,mainPOID.POID,TTm.ID,TTMAmount=TTMD.InvoiceAmount
From TTBeforeMms TTM
inner join TTBeforeMms_Detail TTMD on TTM.ID = TTMD.ID
inner join (
select distinct main.EstAPDate,main_D.POID
From AP main
left join AP_Detail main_D on main.ID = main_D.ID
where main.Type ='PA' and main.EstAPDate between '2018/6/01' AND '2018/6/15' and left(main_D.InvoiceNo,4) != '1111' ) mainPOID on TTMD.poid =mainPOID.POID and TTM.EstAPdate<=mainPOID.EstAPdate and mainPOID.POID='CM3PU18030009'
order by mainPOID.EstAPDate,mainPOID.POID
sql result will like this
My question is
How can Data show by list when group by is not include data?
For example
ID will show by list When I group by EstAPDate、POID and sum(TTMAmount)
You can store in one temp table or use CTE
CREATE TABLE [dbo].#Columnss(
espapdate date ,
poid varchar(max),
id varchar(max),amount decimal(22,6))
GO
insert into #Columnss values('2018-06-15','cm3','pt20',19988.8900)
insert into #Columnss values('2018-06-15','cm3','pt21',265.8900)
SELECT
REPLACE(ESPAPDATE,'-','/') ESPAPDATE, POID,
STUFF(
(SELECT ' , ' + OD.ID
FROM #COLUMNSS OD
WHERE OD.ESPAPDATE = O.ESPAPDATE
AND OD.POID = O.POID
FOR XML PATH('')), 1, 2, ''
) PRODUCTNAMES,SUM(AMOUNT)AMOUNT
FROM #COLUMNSS O
GROUP BY ESPAPDATE, POID
output
espapdate poid ProductNames amount
2018/06/15 cm3 pt20 , pt21 20254.780000
there are lots of CSV example using FOR XML PATH. For your case here, i am wrapping your existing query in a CTE and then from there generate the CSV string for ID
; with
cte as
(
select mainPOID.EstAPDate, mainPOID.POID, TTm.ID, TTMAmount=TTMD.InvoiceAmount
From TTBeforeMms TTM
inner join TTBeforeMms_Detail TTMD on TTM.ID = TTMD.ID
inner join (
select distinct main.EstAPDate,main_D.POID
From AP main
left join AP_Detail main_D on main.ID = main_D.ID
where main.Type ='PA'
and main.EstAPDate between '2018/6/01' AND '2018/6/15'
and left(main_D.InvoiceNo,4) != '1111'
) mainPOID on TTMD.poid = mainPOID.POID
and TTM.EstAPdate <= mainPOID.EstAPdate
and mainPOID.POID = 'CM3PU18030009'
)
SELECT EstAPDate, POID,
ID = STUFF(c.ID, 1, 1, ''),
TTMAmount = SUM(TTMAmount)
FROM cte
CROSS APPLY
(
SELECT ',' + ID
FROM cte x
WHERE x.EstAPDate = cte.EstAPDate
AND x.POID = cte.POID
FOR XML PATH ('')
) c (ID)
GROUP BY EstAPDate, POID
ORDER BY EstAPDate, POID
I'm writing SQL against a Progress 10.2B07 database and am getting the following error "Column 'OUTERINVOICEHEADER.MEMBERID' cannot be found or is not specified for query (13865).
Here is the query:
select concat(substring(OuterInvoiceHeader.sold_to_cust_nbr, 1, 6) + '-', OuterInvoiceHeader.sold_to_cust_seq) as MemberID,
sum(OuterInvoiceHeader.net_weight) as TotalInvoicePounds,
sum(OuterInvoiceHeader.net_weight / 2000) as TotalTons,
sum(OuterInvoiceHeader.invoice_amt) as InvoiceAmount,
sum(InvoiceSurcharges.Surcharge) as Surcharges,
sum(OuterInvoiceHeader.invoice_amt - InvoiceSurcharges.Surcharge) as Total,
sum(Returns.qty_received) as PoundsReturned
from AXS.PUB.ivc_header OuterInvoiceHeader
inner join
(select m.invoice_nbr, sum(m.extension) Surcharge from AXS.PUB.ivc_mchgs m
inner join
AXS.PUB.ivc_header h
on h.invoice_nbr = m.invoice_nbr
group by m.invoice_nbr) InvoiceSurcharges
on OuterInvoiceHeader.invoice_nbr = InvoiceSurcharges.invoice_nbr
left outer join
(select concat(substring(ReturnHeader.ship_to_nbr, 1, 6)+'-',InnerInvoiceHeader.sold_to_cust_seq) as ReturnMemberID,
ReturnHeader.invoice_nbr as ReturnInvoiceNum,
qty_received
from AXS.PUB.return_hdr ReturnHeader
inner join
AXS.PUB.ivc_header InnerInvoiceHeader
on ReturnHeader.invoice_nbr = InnerInvoiceHeader.invoice_nbr
inner join AXS.PUB.return_line ReturnLine
on ReturnHeader.claim_nbr = ReturnLine.claim_nbr
where ReturnInvoiceNum = '0001010914'
group by ReturnMemberID, ReturnInvoiceNum, qty_received) Returns
on OuterInvoiceHeader.MemberID = Returns.ReturnMemberID
--on OuterInvoiceHeader.invoice_nbr = Returns.ReturnInvoiceNum
where OuterInvoiceHeader.sold_to_cust_nbr = '000837' and OuterInvoiceHeader.invoice_date between '06/01/2016' and '06/30/2016' and OuterInvoiceHeader.invoice_status = '5804' and OuterInvoiceHeader.invoice_type='5601'
group by MemberID
The problem is in the left join; the commented out on clause "on OuterInvoiceHeader.invoice_nbr = Returns.ReturnInvoiceNum" will work if uncommented. The "on OuterInvoiceHeader.MemberID = Returns.ReturnMemberID" clause gives me the error.
What I don't understand is that both of these reference a column in the top SELECT statement, the only difference is that one is a concatenation and the other is not.
I hope that I just can't see the forest for the trees here and the answer is simple, so if anyone has any suggestions or questions I'm all ears.
try this:
I replaced the references to the alias MemberID to be the actual concatinated columns CONCAT(SUBSTRING(OuterInvoiceHeader.sold_to_cust_nbr, 1, 6)+'-', OuterInvoiceHeader.sold_to_cust_seq)
SELECT CONCAT(SUBSTRING(OuterInvoiceHeader.sold_to_cust_nbr, 1, 6)+'-', OuterInvoiceHeader.sold_to_cust_seq) AS MemberID
, SUM(OuterInvoiceHeader.net_weight) AS TotalInvoicePounds
, SUM(OuterInvoiceHeader.net_weight / 2000) AS TotalTons
, SUM(OuterInvoiceHeader.invoice_amt) AS InvoiceAmount
, SUM(InvoiceSurcharges.Surcharge) AS Surcharges
, SUM(OuterInvoiceHeader.invoice_amt - InvoiceSurcharges.Surcharge) AS Total
, SUM(Returns.qty_received) AS PoundsReturned
FROM AXS.PUB.ivc_header OuterInvoiceHeader
INNER JOIN
(SELECT m.invoice_nbr
, SUM(m.extension) Surcharge
FROM AXS.PUB.ivc_mchgs m
INNER JOIN AXS.PUB.ivc_header h ON h.invoice_nbr = m.invoice_nbr
GROUP BY m.invoice_nbr) InvoiceSurcharges ON OuterInvoiceHeader.invoice_nbr = InvoiceSurcharges.invoice_nbr
LEFT OUTER JOIN
(SELECT CONCAT(SUBSTRING(ReturnHeader.ship_to_nbr, 1, 6)+'-', InnerInvoiceHeader.sold_to_cust_seq) AS ReturnMemberID
, ReturnHeader.invoice_nbr AS ReturnInvoiceNum
, qty_received
FROM AXS.PUB.return_hdr ReturnHeader
INNER JOIN AXS.PUB.ivc_header InnerInvoiceHeader ON ReturnHeader.invoice_nbr = InnerInvoiceHeader.invoice_nbr
INNER JOIN AXS.PUB.return_line ReturnLine ON ReturnHeader.claim_nbr = ReturnLine.claim_nbr
WHERE ReturnInvoiceNum = '0001010914'
GROUP BY ReturnMemberID
, ReturnInvoiceNum
, qty_received) Returns ON CONCAT(SUBSTRING(OuterInvoiceHeader.sold_to_cust_nbr, 1, 6)+'-', OuterInvoiceHeader.sold_to_cust_seq) = Returns.ReturnMemberID
--on OuterInvoiceHeader.invoice_nbr = Returns.ReturnInvoiceNum
WHERE OuterInvoiceHeader.sold_to_cust_nbr = '000837'
AND OuterInvoiceHeader.invoice_date BETWEEN '06/01/2016' AND '06/30/2016'
AND OuterInvoiceHeader.invoice_status = '5804'
AND OuterInvoiceHeader.invoice_type = '5601'
GROUP BY CONCAT(SUBSTRING(OuterInvoiceHeader.sold_to_cust_nbr, 1, 6)+'-', OuterInvoiceHeader.sold_to_cust_seq);
Basically you need to keep in mind the order which SQL statements are executed:
FROM clause
WHERE clause
GROUP BY clause
HAVING clause
SELECT clause
ORDER BY clause
That's a computed column alias and thus the error. You should consider using the entire expression rather like
on concat(substring(OuterInvoiceHeader.sold_to_cust_nbr, 1, 6) + '-', OuterInvoiceHeader.sold_to_cust_seq) = Returns.ReturnMemberID
Instead of on OuterInvoiceHeader.MemberID = Returns.ReturnMemberID. As well, change any other place where you are using the same alias. You can and should use that alias only in a outer query and not in the same query.
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...
)
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"