Can't make one valid view from multiple tables , i have data duplication problem - sql

I have to unite more than 12 tables value in one view and I should make it with the help of view. Here are two selects which show us what kind of data I should have in a view, I have tried view's several combination but nothing of them were helpful, they provide too many duplicates.
What should I do to get rid of these duplicates?
Here are my two selects and my views example.
First table
SELECT DISTINCT
,ISNULL(SoxInf.InformationGUID,'') AS EntryGuid
,ISNULL([Entry].EntryGUID,'') AS LineGuid
,ISNULL([Entry].LineNumber,0) AS LineNum
,ISNULL([Entry].productID,0) AS Productid
,ISNULL([Entry].ProductName,'') AS ProductNum
,ISNULL([Entry].CommercialDescription,'') AS ProductDesc
,ISNULL([Entry].Brand,'') AS StyleNum
,ISNULL([Entry].TaxIDOfManufacturer,'') AS ManufacturerID
,ISNULL([Entry].ManufacturerInfo,'') AS ManufacturerName
,ISNULL([Entry].GrossWeight,0) AS GrossWeight
,ISNULL([Entry].NetWeight,0) AS NetWeight
,ISNULL([Entry].NumberOfUnits,0) AS TxnQty
,ISNULL([Entry].TypeOfUnits,'') AS TxnQtyUOM
,ISNULL([Entry].SumValue,0) AS TotalValue
,ISNULL([Entry].StatisticalAmount,0) AS RptQty
,ISNULL(TaxInsurence.Rate,0) AS ExactRate
,ISNULL(TaxInsurence.Amount,0) AS Duty
,ISNULL(TaxInsurence.Amount,0) + ISNULL(Calculate.AddlDuty,0) AS TotalDuty
,ISNULL(BorderTax.Amount,0) AS TotalBorderTaxValue
,ISNULL(CustomerTax.Amount,0) AS TotalCustomerTaxValue
,ISNULL(OtherTax.Amount,0) AS TotalOtherTaxValue
,ISNULL(SoxInf.CountryOfDeparture,0) AS ExportCountry
,ISNULL(SoxInf.Term,'') AS Terms
,ISNULL(SoxInf.RelationshipOfBuyerAndSeller,'') AS RelatedPartyFlag
,LocalPortExpenses + OtherLocalExpenses + FreightAmount + InsuranceAmount + TresspassingFeeAtTheBorder AS Fees
,ISNULL(TotalCalculate.TotalAVeragePayments,0) AS TotalSummedPayments
FROM
[Incoming] Incoming
LEFT JOIN
[Documentinformation] SoxInf ON SoxInf.IncomingGUID = Incoming.IncomingGUID
AND SoxInf.PartnerId = Incoming.PartnerId
LEFT JOIN
[IncomingDocuments] Document ON Document.InformationGUID = SoxInf.InformationGUID
LEFT JOIN
[IncomingEntryDocument] [Entry] ON [Entry].InformationGUID = SoxInf.InformationGUID
LEFT JOIN
(SELECT
SoxInf.InformationGUID AS DocumentExtraInformationGUID
,SoxInf.PartnerId AS PartnerId
,(SoxInf.CounterveilingDuty * (ISNULL([Entry].SumValue,0) / ISNULL(NULLIF(EntrySum.SumSumValue,0),1))) AS AddlDuty
FROM
[Documentinformation] SoxInf
LEFT JOIN
[IncomingEntryDocument] [Entry] ON [Entry].InformationGUID = SoxInf.InformationGUID
AND
LEFT JOIN
(SELECT
DocumentExtraInformationGUID, SUM(SumValue) AS SumSumValue
FROM
[IncomingEntryDocument]
GROUP BY
DocumentExtraInformationGUID) EntrySum ON EntrySum.InformationGUID = SoxInf.InformationGUID
GROUP BY
SoxInf.DocumentExtraInformationGUID
,SoxInf.PartnerId
,SoxInf.CounterveilingDuty
,[Entry].SumValue
,EntrySum.SumSumValue) Calculate ON Calculate.InformationGUID = SoxInf.InformationGUID
AND
LEFT JOIN
(SELECT
SoxInf.InformationGUID AS DocumentExtraInformationGUID
,(ISNULL(TaxInsurence.Amount,0) + (SoxInf.CounterveilingDuty * (ISNULL([Entry].SumValue,0) / ISNULL(NULLIF(EntrySum.SumSumValue,0),1)))
+ ISNULL(BorderTax.Amount,0) + ISNULL(CustomerTax.Amount,0) + ISNULL(OtherTax.Amount,0)
+ ISNULL([Entry].LocalPortExpenses,0) + ISNULL([Entry].OtherLocalExpenses,0)
+ ISNULL([Entry].FreightAmount,0) + ISNULL([Entry].InsuranceAmount,0)
+ ISNULL([Entry].TresspassingFeeAtTheBorder,0)) AS TotalAVeragePayments
FROM [Documentinformation] SoxInf
LEFT JOIN [IncomingEntryDocument] [Entry]
ON [Entry].InformationGUID = SoxInf.InformationGUID AND [Entry].PartnerID = SoxInf.PartnerId
LEFT JOIN (
SELECT DocumentExtraInformationGUID, PartnerID, SUM(SumValue) AS SumSumValue
FROM [IncomingEntryDocument]
GROUP BY DocumentExtraInformationGUID, PartnerID) EntrySum
ON EntrySum.InformationGUID = SoxInf.InformationGUID
LEFT JOIN [EntryTaxInformation] TaxInsurence
ON TaxInsurence.InformationGUID = SoxInf.InformationGUID
AND TaxInsurence.Code = '10'
LEFT JOIN [EntryTaxInformation] BorderTax
ON BorderTax.InformationGUID = SoxInf.InformationGUID
AND BorderTax.Code = '40'
LEFT JOIN [EntryTaxInformation] CustomerTax
ON CustomerTax.InformationGUID = SoxInf.InformationGUID
LEFT JOIN [EntryTaxInformation] OtherTax
ON OtherTax.InformationGUID = SoxInf.InformationGUID
AND OtherTax.Code = '89'
GROUP BY SoxInf.DocumentExtraInformationGUID
,TaxInsurence.Amount
,BorderTax.Amount
,CustomerTax.Amount
,OtherTax.Amount
,SoxInf.CounterveilingDuty
,[Entry].SumValue
,EntrySum.SumSumValue
,[Entry].LocalPortExpenses
,[Entry].OtherLocalExpenses
,[Entry].FreightAmount
,[Entry].InsuranceAmount
,[Entry].TresspassingFeeAtTheBorder
) TotalCalculate
ON TotalCalculate.InformationGUID = SoxInf.InformationGUID
LEFT JOIN EntryTaxInformation TaxInsurence
ON TaxInsurence.InformationGUID = SoxInf.InformationGUID
AND TaxInsurence.Code = '10'
LEFT JOIN [EntryTaxInformation] BorderTax
ON BorderTax.InformationGUID = SoxInf.InformationGUID
AND BorderTax.Code = '40'
LEFT JOIN [EntryTaxInformation] CustomerTax
ON CustomerTax.InformationGUID = SoxInf.InformationGUID
AND CustomerTax.Code = '93'
LEFT JOIN [EntryTaxInformation] OtherTax
ON OtherTax.InformationGUID = SoxInf.InformationGUID
AND OtherTax.Code = '89'
Second Table
SELECT DISTINCT
ISNULL(Inf.InformationGUID,'') AS EntryRecordGuid
,ISNULL(Inf.RegistryNumber,'') AS Num
,ISNULL(Inf.TaxIDOfTheDeclarant,'') AS BrokerID
,ISNULL(Inf.TypeOfDocument,'') AS DocumentType
,ISNULL(Inf.CustomerId,'') AS CustomerID
,ISNULL(Inf.RelatedReference,'') AS ReferenceNum
,CONVERT(DATETIME,(SELECT MAX(ISNULL(Document.DocumentDate,'')) FROM [EntryRecordDocument] Document
WHERE Document.InformationGUID = Inf.InformationGUID
GROUP BY Document.InformationGUID),104) AS Registration
,CONVERT(DATETIME,(SELECT MAX(ISNULL(Document.DocumentDate,'')) FROM [EntryRecordDocument] Document
WHERE Document.InformationGUID = Inf.InformationGUID
GROUP BY Document.InformationGUID),104) AS Eidt
,CONVERT(DATETIME,(SELECT MAX(ISNULL(Document.ApprovalDate,'')) FROM [EntryRecordDocument] Document
WHERE Document.InformationGUID = Inf.InformationGUID
GROUP BY Document.InformationGUID),104) AS ReleaseDate
,ISNULL(Inf.TypeOfVehicleAtTheBorder,'') AS ModeOfTransport
,CONVERT(varchar(6),FLOOR(ISNULL([EntryRecord].LocalPort,0))) AS PortOfFiling
,SUM(DutyCalculate.Duty) AS TotalPaymentValue
,SUM(LocalPortExpenses + OtherLocalExpenses + FreightAmount + InsuranceAmount + TresspassingFeeAtTheBorder) AS TotalFees
,SUM(DeclarationPaymentsCalculate.DeclarationPayments) AS TotalDeclarationPayments
FROM [Incoming] Incoming
LEFT JOIN [Documentinformation] Inf
ON Inf.IncomingGUID = Incoming.IncomingGUID
LEFT JOIN [EntryRecordInformation] [EntryRecord]
ON [EntryRecord].InformationGUID = Inf.InformationGUID
LEFT JOIN (
SELECT Inf.InformationGUID AS InformationGUID
,(ISNULL(Tax.Amount,0) + (Inf.CounterveilingDuty * (ISNULL([EntryRecord].StatisticValue,0) / ISNULL(NULLIF(EntryRecordSum.SumStatisticValue,0),1)))) AS Duty
FROM [Documentinformation] Inf
LEFT JOIN [EntryRecordInformation] [EntryRecord]
ON [EntryRecord].InformationGUID = Inf.InformationGUID
LEFT JOIN (
SELECT InformationGUID, PartnerID, SUM(StatisticValue) AS SumStatisticValue
FROM [EntryRecordInformation]
GROUP BY InformationGUID, PartnerID) EntryRecordSum
ON EntryRecordSum.InformationGUID = Inf.InformationGUID
LEFT JOIN [EntryRecordTax] Tax
ON Tax.InformationGUID = Inf.InformationGUID
AND Tax.Code = '10'
GROUP BY Inf.InformationGUID
,Tax.Amount
,Inf.CounterveilingDuty
,[EntryRecord].StatisticValue
,EntryRecordSum.SumStatisticValue
) DutyCalculate
ON DutyCalculate.InformationGUID = Inf.InformationGUID
LEFT JOIN(
SELECT Inf.InformationGUID AS InformationGUID
,(ISNULL(TaxInsurence.Amount,0) + (Inf.CounterveilingDuty * (ISNULL([EntryRecord].StatisticValue,0) / ISNULL(NULLIF(EntryRecordSum.SumStatisticValue,0),1)))
+ ISNULL(BorderTax.Amount,0) + ISNULL(CustomerTax.Amount,0) + ISNULL(OtherTax.Amount,0)
+ ISNULL([EntryRecord].LocalPortExpenses,0) + ISNULL([EntryRecord].OtherLocalExpenses,0)
+ ISNULL([EntryRecord].FreightAmount,0) + ISNULL([EntryRecord].InsuranceAmount,0)
+ ISNULL([EntryRecord].TresspassingFeeAtTheBorder,0)) AS DeclarationPayments
FROM [Documentinformation] Inf
LEFT JOIN [EntryRecordInformation] [EntryRecord]
ON [EntryRecord].InformationGUID = Inf.InformationGUID AND [EntryRecord].PartnerID = Inf.PartnerId
LEFT JOIN (
SELECT InformationGUID, PartnerID, SUM(StatisticValue) AS SumStatisticValue
FROM [EntryRecordInformation]
GROUP BY InformationGUID, PartnerID) EntryRecordSum
ON EntryRecordSum.InformationGUID = Inf.InformationGUID
LEFT JOIN [EntryRecordTax] TaxInsurence
ON TaxInsurence.InformationGUID = Inf.InformationGUID
AND TaxInsurence.Code = '10'
LEFT JOIN [EntryRecordTax] BorderTax
ON BorderTax.InformationGUID = Inf.InformationGUID
AND BorderTax.Code = '40'
LEFT JOIN [EntryRecordTax] CustomerTax
ON CustomerTax.InformationGUID = Inf.InformationGUID
AND CustomerTax.Code = '93'
LEFT JOIN [EntryRecordTax] OtherTax
ON OtherTax.InformationGUID = Inf.InformationGUID
AND OtherTax.Code = '89'
GROUP BY Inf.InformationGUID
,TaxInsurence.Amount
,BorderTax.Amount
,CustomerTax.Amount
,OtherTax.Amount
,Inf.CounterveilingDuty
,[EntryRecord].StatisticValue
,EntryRecordSum.SumStatisticValue
,[EntryRecord].LocalPortExpenses
,[EntryRecord].OtherLocalExpenses
,[EntryRecord].FreightAmount
,[EntryRecord].InsuranceAmount
,[EntryRecord].TresspassingFeeAtTheBorder
) DeclarationPaymentsCalculate
ON DeclarationPaymentsCalculate.InformationGUID = Inf.InformationGUID
GROUP BY Inf.InformationGUID
,Inf.RegistryNumber
,Inf.TaxIDOfTheDeclarant
,Inf.TypeOfDocument
,Inf.CustomerId
,Inf.RelatedReference
,Inf.TypeOfVehicleAtTheBorder
My view
CREATE VIEW
AS
SELECT DISTINCT
,ISNULL(SoxInf.InformationGUID,'') AS EntryGuid
,ISNULL([Entry].EntryGUID,'') AS LineGuid
,ISNULL([Entry].LineNumber,0) AS LineNum
,ISNULL([Entry].productID,0) AS Productid
,ISNULL([Entry].ProductName,'') AS ProductNum
,ISNULL([Entry].CommercialDescription,'') AS ProductDesc
,ISNULL([Entry].Brand,'') AS StyleNum
,ISNULL([Entry].TaxIDOfManufacturer,'') AS ManufacturerID
,ISNULL([Entry].ManufacturerInfo,'') AS ManufacturerName
,ISNULL([Entry].GrossWeight,0) AS GrossWeight
,ISNULL([Entry].NetWeight,0) AS NetWeight
,ISNULL([Entry].NumberOfUnits,0) AS TxnQty
,ISNULL([Entry].TypeOfUnits,'') AS TxnQtyUOM
,ISNULL([Entry].SumValue,0) AS TotalValue
,ISNULL([Entry].StatisticalAmount,0) AS RptQty
,ISNULL(TaxInsurence.Rate,0) AS ExactRate
,ISNULL(TaxInsurence.Amount,0) AS Duty
,ISNULL(TaxInsurence.Amount,0) + ISNULL(Calculate.AddlDuty,0) AS TotalDuty
,ISNULL(BorderTax.Amount,0) AS TotalBorderTaxValue
,ISNULL(CustomerTax.Amount,0) AS TotalCustomerTaxValue
,ISNULL(OtherTax.Amount,0) AS TotalOtherTaxValue
,ISNULL(SoxInf.CountryOfDeparture,0) AS ExportCountry
,ISNULL(SoxInf.Term,'') AS Terms
,ISNULL(SoxInf.RelationshipOfBuyerAndSeller,'') AS RelatedPartyFlag
,LocalPortExpenses + OtherLocalExpenses + FreightAmount + InsuranceAmount + TresspassingFeeAtTheBorder AS Fees
,ISNULL(TotalCalculate.TotalAVeragePayments,0) AS TotalSummedPayments
,ISNULL(Inf.InformationGUID,'') AS EntryRecordGuid
,ISNULL(Inf.RegistryNumber,'') AS Num
,ISNULL(Inf.TaxIDOfTheDeclarant,'') AS BrokerID
,ISNULL(Inf.TypeOfDocument,'') AS DocumentType
,ISNULL(Inf.CustomerId,'') AS CustomerID
,ISNULL(Inf.RelatedReference,'') AS ReferenceNum
,CONVERT(DATETIME,(SELECT MAX(ISNULL(Document.DocumentDate,'')) FROM [EntryRecordDocument] Document
WHERE Document.InformationGUID = Inf.InformationGUID
GROUP BY Document.InformationGUID),104) AS Registration
,CONVERT(DATETIME,(SELECT MAX(ISNULL(Document.DocumentDate,'')) FROM [EntryRecordDocument] Document
WHERE Document.InformationGUID = Inf.InformationGUID
GROUP BY Document.InformationGUID),104) AS Eidt
,CONVERT(DATETIME,(SELECT MAX(ISNULL(Document.ApprovalDate,'')) FROM [EntryRecordDocument] Document
WHERE Document.InformationGUID = Inf.InformationGUID
GROUP BY Document.InformationGUID),104) AS ReleaseDate
,ISNULL(Inf.TypeOfVehicleAtTheBorder,'') AS ModeOfTransport
,CONVERT(varchar(6),FLOOR(ISNULL([EntryRecord].LocalPort,0))) AS PortOfFiling
,SUM(DutyCalculate.Duty) AS TotalPaymentValue
,SUM(LocalPortExpenses + OtherLocalExpenses + FreightAmount + InsuranceAmount + TresspassingFeeAtTheBorder) AS TotalFees
,SUM(DeclarationPaymentsCalculate.DeclarationPayments) AS TotalDeclarationPayments
FROM [Incoming] Incoming
LEFT JOIN [Documentinformation] Inf
ON Inf.IncomingGUID = Incoming.IncomingGUID
LEFT JOIN [EntryRecordInformation] [EntryRecord]
ON [EntryRecord].InformationGUID = Inf.InformationGUID
--join from another table--
LEFT JOIN (
SELECT SoxInf.InformationGUID AS DocumentExtraInformationGUID
,SoxInf.PartnerId AS PartnerId
,(SoxInf.CounterveilingDuty * (ISNULL([Entry].SumValue,0) / ISNULL(NULLIF(EntrySum.SumSumValue,0),1))) AS AddlDuty
FROM [Documentinformation] SoxInf
LEFT JOIN [IncomingEntryDocument] [Entry]
ON [Entry].InformationGUID = SoxInf.InformationGUID AND
LEFT JOIN (
SELECT DocumentExtraInformationGUID, SUM(SumValue) AS SumSumValue
FROM [IncomingEntryDocument]
GROUP BY DocumentExtraInformationGUID) EntrySum
ON EntrySum.InformationGUID = SoxInf.InformationGUID
GROUP BY SoxInf.DocumentExtraInformationGUID
,SoxInf.PartnerId
,SoxInf.CounterveilingDuty
,[Entry].SumValue
,EntrySum.SumSumValue
) Calculate
ON Calculate.InformationGUID = SoxInf.InformationGUID AND
LEFT JOIN(
SELECT SoxInf.InformationGUID AS DocumentExtraInformationGUID
,(ISNULL(TaxInsurence.Amount,0) + (SoxInf.CounterveilingDuty * (ISNULL([Entry].SumValue,0) / ISNULL(NULLIF(EntrySum.SumSumValue,0),1)))
+ ISNULL(BorderTax.Amount,0) + ISNULL(CustomerTax.Amount,0) + ISNULL(OtherTax.Amount,0)
+ ISNULL([Entry].LocalPortExpenses,0) + ISNULL([Entry].OtherLocalExpenses,0)
+ ISNULL([Entry].FreightAmount,0) + ISNULL([Entry].InsuranceAmount,0)
+ ISNULL([Entry].TresspassingFeeAtTheBorder,0)) AS TotalAVeragePayments
FROM [Documentinformation] SoxInf
LEFT JOIN [IncomingEntryDocument] [Entry]
ON [Entry].InformationGUID = SoxInf.InformationGUID AND [Entry].PartnerID = SoxInf.PartnerId
LEFT JOIN (
SELECT DocumentExtraInformationGUID, PartnerID, SUM(SumValue) AS SumSumValue
FROM [IncomingEntryDocument]
GROUP BY DocumentExtraInformationGUID, PartnerID) EntrySum
ON EntrySum.InformationGUID = SoxInf.InformationGUID
LEFT JOIN [EntryTaxInformation] TaxInsurence
ON TaxInsurence.InformationGUID = SoxInf.InformationGUID
AND TaxInsurence.Code = '10'
LEFT JOIN [EntryTaxInformation] BorderTax
ON BorderTax.InformationGUID = SoxInf.InformationGUID
AND BorderTax.Code = '40'
LEFT JOIN [EntryTaxInformation] CustomerTax
ON CustomerTax.InformationGUID = SoxInf.InformationGUID
LEFT JOIN [EntryTaxInformation] OtherTax
ON OtherTax.InformationGUID = SoxInf.InformationGUID
AND OtherTax.Code = '89'
GROUP BY SoxInf.DocumentExtraInformationGUID
,TaxInsurence.Amount
,BorderTax.Amount
,CustomerTax.Amount
,OtherTax.Amount
,SoxInf.CounterveilingDuty
,[Entry].SumValue
,EntrySum.SumSumValue
,[Entry].LocalPortExpenses
,[Entry].OtherLocalExpenses
,[Entry].FreightAmount
,[Entry].InsuranceAmount
,[Entry].TresspassingFeeAtTheBorder
) TotalCalculate
ON TotalCalculate.InformationGUID = SoxInf.InformationGUID
LEFT JOIN EntryTaxInformation TaxInsurence
ON TaxInsurence.InformationGUID = SoxInf.InformationGUID
AND TaxInsurence.Code = '10'
LEFT JOIN [EntryTaxInformation] BorderTax
ON BorderTax.InformationGUID = SoxInf.InformationGUID
AND BorderTax.Code = '40'
LEFT JOIN [EntryTaxInformation] CustomerTax
ON CustomerTax.InformationGUID = SoxInf.InformationGUID
AND CustomerTax.Code = '93'
LEFT JOIN [EntryTaxInformation] OtherTax
ON OtherTax.InformationGUID = SoxInf.InformationGUID
AND OtherTax.Code = '89'
--end of join on another table--
LEFT JOIN (
SELECT Inf.InformationGUID AS InformationGUID
,(ISNULL(Tax.Amount,0) + (Inf.CounterveilingDuty * (ISNULL([EntryRecord].StatisticValue,0) / ISNULL(NULLIF(EntryRecordSum.SumStatisticValue,0),1)))) AS Duty
FROM [Documentinformation] Inf
LEFT JOIN [EntryRecordInformation] [EntryRecord]
ON [EntryRecord].InformationGUID = Inf.InformationGUID
LEFT JOIN (
SELECT InformationGUID, PartnerID, SUM(StatisticValue) AS SumStatisticValue
FROM [EntryRecordInformation]
GROUP BY InformationGUID, PartnerID) EntryRecordSum
ON EntryRecordSum.InformationGUID = Inf.InformationGUID
LEFT JOIN [EntryRecordTax] Tax
ON Tax.InformationGUID = Inf.InformationGUID
AND Tax.Code = '10'
GROUP BY Inf.InformationGUID
,Tax.Amount
,Inf.CounterveilingDuty
,[EntryRecord].StatisticValue
,EntryRecordSum.SumStatisticValue
) DutyCalculate
ON DutyCalculate.InformationGUID = Inf.InformationGUID
LEFT JOIN(
SELECT Inf.InformationGUID AS InformationGUID
,(ISNULL(TaxInsurence.Amount,0) + (Inf.CounterveilingDuty * (ISNULL([EntryRecord].StatisticValue,0) / ISNULL(NULLIF(EntryRecordSum.SumStatisticValue,0),1)))
+ ISNULL(BorderTax.Amount,0) + ISNULL(CustomerTax.Amount,0) + ISNULL(OtherTax.Amount,0)
+ ISNULL([EntryRecord].LocalPortExpenses,0) + ISNULL([EntryRecord].OtherLocalExpenses,0)
+ ISNULL([EntryRecord].FreightAmount,0) + ISNULL([EntryRecord].InsuranceAmount,0)
+ ISNULL([EntryRecord].TresspassingFeeAtTheBorder,0)) AS DeclarationPayments
FROM [Documentinformation] Inf
LEFT JOIN [EntryRecordInformation] [EntryRecord]
ON [EntryRecord].InformationGUID = Inf.InformationGUID AND [EntryRecord].PartnerID = Inf.PartnerId
LEFT JOIN (
SELECT InformationGUID, PartnerID, SUM(StatisticValue) AS SumStatisticValue
FROM [EntryRecordInformation]
GROUP BY InformationGUID, PartnerID) EntryRecordSum
ON EntryRecordSum.InformationGUID = Inf.InformationGUID
LEFT JOIN [EntryRecordTax] TaxInsurence
ON TaxInsurence.InformationGUID = Inf.InformationGUID
AND TaxInsurence.Code = '10'
LEFT JOIN [EntryRecordTax] BorderTax
ON BorderTax.InformationGUID = Inf.InformationGUID
AND BorderTax.Code = '40'
LEFT JOIN [EntryRecordTax] CustomerTax
ON CustomerTax.InformationGUID = Inf.InformationGUID
AND CustomerTax.Code = '93'
LEFT JOIN [EntryRecordTax] OtherTax
ON OtherTax.InformationGUID = Inf.InformationGUID
AND OtherTax.Code = '89'
GROUP BY Inf.InformationGUID
,TaxInsurence.Amount
,BorderTax.Amount
,CustomerTax.Amount
,OtherTax.Amount
,Inf.CounterveilingDuty
,[EntryRecord].StatisticValue
,EntryRecordSum.SumStatisticValue
,[EntryRecord].LocalPortExpenses
,[EntryRecord].OtherLocalExpenses
,[EntryRecord].FreightAmount
,[EntryRecord].InsuranceAmount
,[EntryRecord].TresspassingFeeAtTheBorder
) DeclarationPaymentsCalculate
ON DeclarationPaymentsCalculate.InformationGUID = Inf.InformationGUID
GROUP BY Inf.InformationGUID
,Inf.RegistryNumber
,Inf.TaxIDOfTheDeclarant
,Inf.TypeOfDocument
,Inf.CustomerId
,Inf.RelatedReference
,Inf.TypeOfVehicleAtTheBorder
I don't face any error, but when i need to have 15 record in my view, because i have 15 id in all my table i got more than 63 ides, what should i manage to get rid of duplicate values?

There are two options:
one is to create a view that aggregates values based on group by, so something like
SELECT t1.something, MAX(t1.somethingElse) as maxElse, MIN(t2.x) as minX
the other is to use RANK (https://learn.microsoft.com/en-us/sql/t-sql/functions/rank-transact-sql) which will return all of the duplicates, but also with rank columns that show their order in the partition. All you have to do then is add another filter:
SELECT * FROM (
SELECT with rank
) t
WHERE t.rank = 1
I think the second one is more correct and more clear, but it depends on your case.

There is a trick to do this in SQL Server. It is really hard to say what the exact syntax is for your query, but you can use top (1) with ties instead of select distinct.
So:
select top (1) with ties . . .
from . . .
. . .
order by row_number() over (partition by <x> order by <y>)
-----------------------------------------^ you'll get one row for each value of this
------------------------------------------------------^ that row will be the first by this
This is really a "hack" solution for what you are doing. If you expect fewer rows, you should fix the underlying query so it returns the rows that you want. It is not clear where those rows come from, and your queries are way to complicated for anyone to figure out.
You will need to simplify, simplify the logic. I would recommend starting with a query that just produces the rows you want. Then add additional joins and columns and other logic to get the columns.

Related

Division by zero in Laravel

I want to ask, Why can I use the first SQL command, the second fails?
Note: Error occurs when data is empty
Success
$barang = KeluarTmp::LeftJoin('data_barang', function($join){
$join->on('data_barang.kode_barang','=','barang_keluar_tmp.kode');
})->leftjoin('data_jasa','barang_keluar_tmp.kode','=','data_jasa.kode_jasa')
->WHERE('barang_keluar_tmp.keterangan', $user)
->orderBy('barang_keluar_tmp.created_at','ASC')
->get(['barang_keluar_tmp.id as id',
'data_barang.nama_barang as nama_barang',
'barang_keluar_tmp.kode as kode_barang',
'barang_keluar_tmp.qty as jumlah',
'barang_keluar_tmp.total_harga as total_harga',
'barang_keluar_tmp.total_harga_awal as total_harga_awal',
'data_jasa.nama_jasa as nama_jasa',
'barang_keluar_tmp.diskon as diskon'
]);
Error Devision Zero
$barang = DB::select('SELECT barang_keluar_tmp.id as id, data_barang.nama_barang as nama_barang, barang_keluar_tmp.kode as kode_barang, barang_keluar_tmp.qty as jumlah, barang_keluar_tmp.total_harga as total_harga, barang_keluar_tmp.total_harga_awal as total_harga_awal, data_jasa.nama_jasa as nama_jasa, barang_keluar_tmp.diskon as diskon, SUM(h.masuk - (i.keluar + barang_keluar_tmp.qty)) as stok
FROM barang_keluar_tmp
JOIN data_barang on data_barang.kode_barang = barang_keluar_tmp.kode
LEFT JOIN data_jasa on barang_keluar_tmp.kode = data_jasa.kode_jasa
LEFT JOIN
(SELECT barang_masuk.kode_barang, SUM(barang_masuk.qty) as masuk from barang_masuk group by barang_masuk.kode_barang)
AS h ON barang_keluar_tmp.kode = h.kode_barang
LEFT JOIN
(SELECT barang_keluar.kode, SUM(barang_keluar.qty) as keluar from barang_keluar group by barang_keluar.kode)
AS i ON barang_keluar_tmp.kode = i.kode
WHERE barang_keluar_tmp.keterangan = "'.$user.'"
ORDER By barang_keluar_tmp.created_at ASC');
use coalesce() on sum()
SELECT barang_keluar_tmp.id as id
, data_barang.nama_barang as nama_barang
, barang_keluar_tmp.kode as kode_barang
, barang_keluar_tmp.qty as jumlah
, barang_keluar_tmp.total_harga as total_harga
, barang_keluar_tmp.total_harga_awal as total_harga_awal
, data_jasa.nama_jasa as nama_jasa, barang_keluar_tmp.diskon as diskon
, SUM(coalesce(h.masuk, 0) - coalesce((i.keluar + barang_keluar_tmp.qty), 0)) as stok
FROM barang_keluar_tmp
JOIN data_barang on data_barang.kode_barang = barang_keluar_tmp.kode
LEFT JOIN data_jasa on barang_keluar_tmp.kode = data_jasa.kode_jasa
LEFT JOIN
(SELECT barang_masuk.kode_barang
, SUM(barang_masuk.qty) as masuk
from barang_masuk
group by barang_masuk.kode_barang)
AS h ON barang_keluar_tmp.kode = h.kode_barang
LEFT JOIN
(SELECT barang_keluar.kode, SUM(barang_keluar.qty) as keluar
from barang_keluar
group by barang_keluar.kode)
AS i ON barang_keluar_tmp.kode = i.kode
WHERE barang_keluar_tmp.keterangan = "'.$user.'"
ORDER By barang_keluar_tmp.created_at ASC

Nested in line view Add Column

I have to add a column to this report - the new column name is: uda_value_desc
The code below will give me a result if I enter a PM_ITEM number, I need to insert the code into one of the in line views.
Any help would be appreciated
WITH item_temp AS (SELECT im.item
,uv.uda_value_desc uda_value_desc -----
FROM item_master im
,TABLE(mff_report.parse_strings(:PM_item)) t
, uda_item_lov uil
, uda_values uv
WHERE t.Column_Value = uil.item
and uil.UDA_ID = 511
and uv.uda_id = uil.uda_id
and uv.uda_value = uil.uda_value
and im.item = uil.item
UNION ALL
SELECT im.item
,null
FROM item_master im
,TABLE(mff_report.parse_strings(:PM_item)) t
WHERE t.COLUMN_VALUE = im.item_parent
AND im.item_level = im.tran_level
UNION ALL
SELECT sd.item
,null
FROM skulist_detail sd
,TABLE(mff_report.parse_strings(:PM_item_list)) t
WHERE t.COLUMN_VALUE = sd.skulist
UNION ALL
SELECT ia.item
,null
FROM mffecom.item_attr ia
,TABLE(mff_report.parse_strings(:PM_product_id)) t
WHERE t.COLUMN_VALUE = ia.product_id
UNION ALL
SELECT im.item
,null
FROM item_master im
WHERE :PM_item IS NULL
AND :PM_item_list IS NULL
AND :PM_product_id IS NULL )
SELECT v_item.item_parent
,uda_value_desc
,v_item.item
,mff_report.mff_merch_sql.get_brand_name(v_item.item) brand_name
,v_item.item_desc
,v_selling.product_id
,v_product.product_web_desc
,v_product.product_template
,v_product.romance_copy
,v_selling.selling_point_1
,v_selling.selling_point_2
,v_selling.selling_point_3
,v_selling.selling_point_4
,v_selling.selling_point_5
,v_selling.selling_point_6
,v_selling.selling_point_7
,v_selling.selling_point_8
,v_selling.selling_point_9
,v_selling.selling_point_10
,v_selling.selling_point_11
,v_selling.selling_point_12
,v_selling.selling_point_13
,v_selling.selling_point_14
,v_selling.selling_point_15
,v_selling.selling_point_16
,v_item.vpn
,v_item.diff_1
,v_item.diff1_desc
,v_item.diff_2
,v_item.diff2_desc
,v_item.diff_3
,v_item.diff3_desc
,v_item.diff_4
,v_item.diff4_desc
,v_item.supplier
,v_item.sup_name
,v_product.code_desc fulfillment_method_desc
,v_product.air_ship_restrict
,v_product.do_not_freeze
,v_product.free_shipping
,v_product.refrigerate
,v_product.serial_reqd
,v_product.vaccination
,v_product.is_consumable
,v_product.zero_weight
,v_product.restrict_state
,v_product.no_of_alt_image
,v_product.product_status
,v_product.item_ecom_status
,TO_CHAR(v_product.deactivate_date, 'MM/DD/YYYY') product_deactivate_date
,TO_CHAR(v_product.product_activate_date, 'MM/DD/YYYY') product_activate_date
,TO_CHAR(v_product.item_activate_date, 'MM/DD/YYYY') item_activate_date
,TO_CHAR(v_product.item_deactivate_date, 'MM/DD/YYYY') item_deactivate_date
,v_product.prod_created_by
,TO_CHAR(v_product.prod_created_date, 'MM/DD/YYYY') prod_created_date
,v_product.prod_updated_by
,v_product.item_created_by
,TO_CHAR(v_product.item_created_date, 'MM/DD/YYYY') item_created_date
,v_product.item_updated_by
,v_item.delete_type purge
,v_item.dept
,v_item.class
,v_item.subclass
,mff_orders_sql.buyer_for_item(v_item.item) buyer
,mff_orders_sql.buyer_name_for_item(v_item.item) buyer_name
,v_item.soh
,v_item.length
,v_item.width
,v_item.height
,v_item.weight
,v_variant.variant_id1
,v_variant.value_id1
,v_variant.variant_id2
,v_variant.value_id2
,v_variant.variant_id3
,v_variant.value_id3
,v_variant.variant_id4
,v_variant.value_id4
,v_variant.variant_id5
,v_variant.value_id5
,v_variant.variant_id6
,v_variant.value_id6
FROM (SELECT ia.item
,v_sell.product_id
,MIN(DECODE(row_num,1,selling_point)) selling_point_1
,MIN(DECODE(row_num,2,selling_point)) selling_point_2
,MIN(DECODE(row_num,3,selling_point)) selling_point_3
,MIN(DECODE(row_num,4,selling_point)) selling_point_4
,MIN(DECODE(row_num,5,selling_point)) selling_point_5
,MIN(DECODE(row_num,6,selling_point)) selling_point_6
,MIN(DECODE(row_num,7,selling_point)) selling_point_7
,MIN(DECODE(row_num,8,selling_point)) selling_point_8
,MIN(DECODE(row_num,9,selling_point)) selling_point_9
,MIN(DECODE(row_num,10,selling_point)) selling_point_10
,MIN(DECODE(row_num,11,selling_point)) selling_point_11
,MIN(DECODE(row_num,12,selling_point)) selling_point_12
,MIN(DECODE(row_num,13,selling_point)) selling_point_13
,MIN(DECODE(row_num,14,selling_point)) selling_point_14
,MIN(DECODE(row_num,15,selling_point)) selling_point_15
,MIN(DECODE(row_num,16,selling_point)) selling_point_16
FROM mffecom.item_attr ia
,(SELECT sp.product_id
,row_number () OVER (PARTITION BY sp.product_id ORDER BY sp.selling_point_id) row_num
,sp.selling_point
FROM mffecom.selling_point sp
ORDER BY sp.product_id
,sp.selling_point) v_sell
WHERE ia.product_id = v_sell.product_id
GROUP BY ia.item
,v_sell.product_id) v_selling
,(SELECT NVL(im.item_parent,im.item) item_parent
,im.item
,im.item_desc
,im.dept
,im.class
,im.subclass
,isupp.supplier
,s.sup_name
,isupp.vpn
,miim.stock_on_hand soh
,iscd.length
,iscd.width
,iscd.height
,iscd.weight
,im.diff_1
,di.diff_desc diff1_desc
,im.diff_2
,di2.diff_desc diff2_desc
,im.diff_3
,di3.diff_desc diff3_desc
,im.diff_4
,di4.diff_desc diff4_desc
,dp.delete_type
FROM item_supplier isupp
,sups s
,item_supp_country_dim iscd
,item_master im
,diff_ids di
,diff_ids di2
,diff_ids di3
,diff_ids di4
,daily_purge dp
,merch_item_inv_mv miim
WHERE isupp.item = im.item
AND isupp.item = miim.item (+)
AND isupp.supplier = s.supplier
AND isupp.item = iscd.item
AND isupp.supplier = iscd.supplier
AND isupp.primary_supp_ind = 'Y'
AND iscd.dim_object = 'EA'
AND im.item_level = im.tran_level
AND im.sellable_ind = 'Y'
AND im.diff_1 = di.diff_id (+)
AND im.diff_2 = di2.diff_id (+)
AND im.diff_3 = di3.diff_id (+)
AND im.diff_4 = di4.diff_id (+)
AND im.item = dp.key_value (+)) v_item
,(SELECT ia.item
,pm.product_id
,pm.product_web_desc
,pm.template product_template
,pm.romance_copy
,ia.air_ship_restrict
,ia.do_not_freeze
,ia.free_shipping
,ia.refrigerate
,ia.serial_reqd
,ia.vaccination
,ia.is_consumable
,ia.zero_weight
,pm.no_of_alt_image
,pm.status product_status
,ia.status item_ecom_status
,pm.deactivate_date deactivate_date
,pm.activate_date product_activate_date
,ia.activate_date item_activate_date
,ia.deactivate_date item_deactivate_date
,pm.created_by prod_created_by
,pm.create_datetime prod_created_date
,pm.updated_by prod_updated_by
,ita.created_by item_created_by
,ita.create_date item_created_date
,ia.updated_by item_updated_by
,str.restrict_state
,cd.code_desc
FROM MFFECOM.product_master pm
,MFFECOM.item_attr ia
,MFFECOM.ship_to_restrict str
,rms13.mff_brand mb
,rms13.item_attributes ita
,rms13.code_detail cd
WHERE ia.product_id = pm.product_id
AND ia.item = str.item (+)
AND ia.item = ita.item (+)
AND pm.brand_id = mb.brand_id (+)
AND to_char(ia.fulfillment_method) = cd.code
AND cd.code_type = 'EIFM') v_product
,(SELECT item
,product_id
,MIN(DECODE(row_num,1,variant_id)) variant_id1
,MIN(DECODE(row_num,1,value_id)) value_id1
,MIN(DECODE(row_num,2,variant_id)) variant_id2
,MIN(DECODE(row_num,2,value_id)) value_id2
,MIN(DECODE(row_num,3,variant_id)) variant_id3
,MIN(DECODE(row_num,3,value_id)) value_id3
,MIN(DECODE(row_num,4,variant_id)) variant_id4
,MIN(DECODE(row_num,4,value_id)) value_id4
,MIN(DECODE(row_num,5,variant_id)) variant_id5
,MIN(DECODE(row_num,5,value_id)) value_id5
,MIN(DECODE(row_num,6,variant_id)) variant_id6
,MIN(DECODE(row_num,6,value_id)) value_id6
FROM (SELECT item
,product_id
,row_number () OVER (PARTITION BY item ORDER BY variant_id) row_num
,variant_id
,value_id
FROM mffecom.item_variant)
GROUP BY item
,product_id) v_variant
,item_temp it
WHERE v_item.item = v_selling.item (+)
AND v_item.item = v_product.item (+)
AND v_item.item = v_variant.item (+)
AND v_item.item = it.item
AND v_item.supplier = NVL(:PM_supplier,v_item.supplier)
AND (v_product.prod_created_by = :PM_prod_created_by OR :PM_prod_created_by IS NULL)
AND (v_product.item_created_by = :PM_item_created_by OR :PM_item_created_by IS NULL)
AND (v_product.prod_created_date BETWEEN :prod_created_date_start AND :prod_created_date_to OR :prod_created_date_start IS NULL)
AND (v_product.item_created_date BETWEEN :item_created_date_start AND :item_created_date_to OR :item_created_date_start IS NULL)
ORDER BY v_product.product_id

Expression.Error Power Query EXCEL

I have a problem with a dynamic parameter in Power Query. There's the code:
let
Parametro = Excel.CurrentWorkbook(){[Name="Parametro"]}[Content],
InicioExec_Valor = Parametro{0}[Valor],
FimExec_Valor = Parametro{1}[Valor],
Fonte = Sql.Database("DATABASE", "TABLE", [Query="select#(lf)#(lf)o.cd_controle, exe.nm_pessoa AS Executante, o.numero AS OM, #(lf)CONVERT(nvarchar(10), o.dt_abertura, 103) AS Abertura,#(lf)o.medidor Horimetro_OM,#(lf)p.nm_pessoa AS Cliente, #(lf)e.nm_equipto AS Equipamento, pat.nr_patrimonio AS Patrimonio, #(lf)CONVERT(nvarchar(10), o.dt_autoriz_execucao, 103) AS Inicio_Exec, #(lf)CONVERT(nvarchar(10), o.dt_encos_oficina, 103) AS Fim_Exec, Z.nm_apelido AS Unidade, #(lf)CASE WHEN fl_preventiva = 'C' THEN 'Corretiva' #(lf)WHEN fl_preventiva = 'P' then 'PREVENTIVA'#(lf)WHEN fl_preventiva = 'R' then 'INSPEÇÃO RESUMIDA'#(lf)WHEN fl_preventiva = 'V' then 'INSPEÇÃO PREVENTIVA'#(lf)WHEN fl_preventiva = 'E' then 'ENTREGA TÉCNICA'#(lf)else 'Indefinido' end AS 'Corret_Preven'#(lf),CONVERT(nvarchar(10), fl_remessa.dt_saida, 103) AS DataSaida#(lf),fl_rem_equ.vl_medidor Horimetro_Remessa#(lf),CONVERT(nvarchar(10), o.dt_abertura, 103) AS Abertura#(lf),o.medidor Horimetro_OM#(lf)#(lf)from orcos o#(lf)inner join controle c on (c.cd_controle = o.cd_controle)#(lf)inner join wcore_oid oid on (oid.cd_oid = c.cd_oid)#(lf)left outer join empresa AS Z ON Z.cd_empresa = o.cd_empresa #(lf)left outer join equipto e on (e.cd_equipto = o.cd_equipto)#(lf)left outer join pessoa f on (f.cd_pessoa = o.cd_pessoa_tec)#(lf)left outer join pessoa p on (p.cd_pessoa = o.cd_pessoa)#(lf)left outer join pessoa exe on (exe.cd_pessoa = o.cd_pessoa_exe)#(lf)left outer join patrimon pat on (pat.cd_patrimonio = o.cd_patrimonio)#(lf)left outer join est_almox x on x.cd_almox = pat.cd_almox#(lf)left outer join empresa emp on emp.cd_empresa = o.cd_empresa_origem #(lf)#(lf)left outer JOIN dbo.fich_loc ON (fich_loc.cd_controle= o.cd_controle_loc)#(lf)left outer JOIN dbo.fl_remessa fl_remessa ON (fl_remessa.cd_controle = dbo.fich_loc.cd_controle)#(lf)#(lf)INNER JOIN(select max(fl_remessa.cd_flremessa)cd_flremessa, A.cd_controle #(lf)#(tab)#(tab)#(tab)#(tab)#(tab) from dbo.fl_remessa#(lf)#(tab)#(tab)#(tab)#(tab)#(tab) inner join dbsislocsalvador..fich_loc on (fl_remessa.cd_controle = dbo.fich_loc.cd_controle)#(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) inner join dbsislocsalvador..orcos a on (fich_loc.cd_controle= A.cd_controle_loc#(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) and fl_remessa.dt_saida<=a.dt_abertura) #(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) inner join controle c on (c.cd_controle = A.cd_controle)#(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) #(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) left outer join patrimon pat on (pat.cd_patrimonio = a.cd_patrimonio)#(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) LEFT OUTER JOIN dbo.fl_rem_equ AS fl_rem_equ ON pat.cd_patrimonio = fl_rem_equ.cd_patrimonio AND fl_remessa.cd_flremessa = fl_rem_equ.cd_flremessa#(lf) #(tab)#(tab) left outer JOIN dbo.loc_flremequ_xplano AS loc_flremequ_xplano ON loc_flremequ_xplano.cd_flremequ = fl_rem_equ.cd_flremequ #(lf) #(tab)#(tab)#(tab) left outer JOIN dbo.equipto AS equipto ON fl_rem_equ.cd_equipto = equipto.cd_equipto#(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) #(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) where #(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) #(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) ((NOT EXISTS(select top 1 * from config_tag_xoid)) OR (c.cd_oid not in (select txo.cd_oid from #(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) (select * from ( select cd_tag, nm_tag , (30) as fl_acesso from config_tag t where t.fl_ativo in ('S') ) tags #(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) WHERE (fl_acesso = 10) ) tags inner join config_tag_xoid txo on tags.cd_tag = txo.cd_tag where 3=3 /*filter_tag_clause*/ #(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) group by txo.cd_oid))) and ( ( (a.cd_controle_loc is not null and a.cd_fldevolucao is null) ) ) and#(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) (a.cd_empresa IN (24,45,5,46,20,29,43,15,48,10,1,22,8,34,49,9,47,52,7)) and ( ( a.cd_local is null or a.cd_local in (0,1,2,3,5,6,7,8,9) ) ) #(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) AND (a.cd_controle_loc IS NOT NULL) AND (a.cd_fldevolucao IS NULL) #(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) and (a.fl_preventiva in ('C', 'P', 'R', 'V', 'E')) #(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) and (equipto.cd_grupo in (1478, 1480, 1481, 1482, 1483, 1484, 1485, 1486, 1487, 1488, 1491, 1492, 1548, 1549))#(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) #(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) group by a.cd_controle) AS fl_remessa_max #(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) ON fl_remessa.cd_flremessa = fl_remessa_max.cd_flremessa#(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) and fl_remessa_max.cd_controle = o.cd_controle #(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) #(lf)LEFT OUTER JOIN dbo.fl_rem_equ AS fl_rem_equ ON pat.cd_patrimonio = fl_rem_equ.cd_patrimonio AND fl_remessa.cd_flremessa = fl_rem_equ.cd_flremessa#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) #(lf)left outer JOIN dbo.equipto AS equipto ON fl_rem_equ.cd_equipto = equipto.cd_equipto#(lf) #(tab)#(tab)#(tab)#(tab)#(tab) #(lf)WHERE ((NOT EXISTS(select top 1 * from config_tag_xoid)) OR (c.cd_oid not in (select txo.cd_oid from #(lf)(select * from ( select cd_tag, nm_tag , (30) as fl_acesso from config_tag t where t.fl_ativo in ('S') ) tags #(lf)WHERE (fl_acesso = 10) ) tags inner join config_tag_xoid txo on tags.cd_tag = txo.cd_tag where 3=3 /*filter_tag_clause*/ #(lf)group by txo.cd_oid))) and ( ( (o.cd_controle_loc is not null and o.cd_fldevolucao is null) ) ) and#(lf)(o.cd_empresa IN (24,45,5,46,20,29,43,15,48,10,1,22,8,34,49,9,47,52,7)) and ( ( o.cd_local is null or o.cd_local in (0,1,2,3,5,6,7,8,9) ) ) #(lf)AND (o.cd_controle_loc IS NOT NULL) AND (o.cd_fldevolucao IS NULL) #(lf)and (o.fl_preventiva in ('C', 'P', 'R', 'V', 'E')) #(lf)and (equipto.cd_grupo in (1478, 1480, 1481, 1482, 1483, 1484, 1485, 1486, 1487, 1488, 1491, 1492, 1548, 1549))"]),
#"Tipo Alterado" = Table.TransformColumnTypes(Fonte,{{"Abertura", type date}, {"Inicio_Exec", type date}, {"Fim_Exec", type date}, {"DataSaida", type date}}),
#"Colunas Removidas" = Table.RemoveColumns(#"Tipo Alterado",{"cd_controle", "Horimetro_OM2", "Abertura2"}),
#"Filtro Datas" = Table.SelectRows(#"Colunas Removidas", each [Fim_Exec] >= InicioExec_Valor and [Fim_Exec] <= FimExec_Valor)
in
#"Filtro Datas"
And occur that error:
Expression.Error: Não conseguimos aplicar o operador < aos tipos
Number e Date. Detalhes:
Operator=<
Left=42795
Right=01/06/2007
How can I solve that?
Note: MY PARAMETER (01/03/2017) ARE FORMATED AS TEXT.
Although I don't read Spanish, looks like it says you cannot compare number and date with < operator.
It is good practice, by the way, to first convert parameters to the proper type:
InicioExec_Valor = Date.From(Parametro{0}[Valor]),
FimExec_Valor = Date.From(Parametro{1}[Valor]),`
Try this.
If it won't work, determine step that generates error by clicking them one-by-one.
There is more I wonder about. Why do you convert Fim_Exec to nvarchar and then to date?
1. #(lf)CONVERT(nvarchar(10), o.dt_encos_oficina, 103) AS Fim_Exec
2. {"Fim_Exec", type date},
Why don't use Fim_Exec = CAST(o.dt_encos_oficina as date)? (or datetime, depending on SQL Server version) in the query?
Same applies to other columns.
Next, it is best practice not to use native queries unless absolutely required.
And, yes, this is largest and most complex query I've seen up to date. :)

syntax error (missing operator) in query expression in MS Access

I'm getting the error:
syntax error (missing operator) in query expression '((dbo_tblBidder.bidder_sale_id = dbo_tblSale.sale_id) AND (dbo_tblSale.sale_id IN (319))) LEFT JOIN
dbo_tblItem ON ((dbo_tblBidder.bidder_sale_id = dbo_tblItem.item_sale_id) AND (dbo_tblBidder.bidder_number = dbo_tblItem.item_bidder_number)'.
I've had this issue before and know that it doesn't like my parenthesis setup, but nothing I do seems to make MS Access happy.
SELECT dbo_tblMailList.mail_FirstName, dbo_tblMailList.mail_LastName, dbo_tblMailList.mail_Address1, dbo_tblMailList.mail_Address2,
dbo_tblMailList.mail_City, dbo_tblMailList.mail_State, dbo_tblMailList.mail_Zip, dbo_tblMailList.mail_Phone1, dbo_tblMailList.mail_Email1,
dbo_tblMailList.mail_Comp_GenAm, dbo_tblBidder.bidder_number, SUM(dbo_tblItem.item_pr) AS SumOfitem_pr, SUM(dbo_tblItem.item_premium)
AS SumOfitem_premium, dbo_tblBidder.bidder_type, dbo_tblSale.sale_id
FROM (dbo_tblMailList LEFT JOIN
dbo_tblBidder ON ((dbo_tblMailList.mail_ID = dbo_tblBidder.bidder_mail_id) AND (dbo_tblBidder.bidder_sale_id IN (319)))) LEFT JOIN
dbo_tblSale ON ((dbo_tblBidder.bidder_sale_id = dbo_tblSale.sale_id) AND (dbo_tblSale.sale_id IN (319))) LEFT JOIN
dbo_tblItem ON ((dbo_tblBidder.bidder_sale_id = dbo_tblItem.item_sale_id) AND (dbo_tblBidder.bidder_number = dbo_tblItem.item_bidder_number))
GROUP BY dbo_tblMailList.mail_FirstName, dbo_tblMailList.mail_LastName, dbo_tblMailList.mail_Address1, dbo_tblMailList.mail_Address2,
dbo_tblMailList.mail_City, dbo_tblMailList.mail_State, dbo_tblMailList.mail_Zip, dbo_tblMailList.mail_Phone1, dbo_tblMailList.mail_Email1,
dbo_tblMailList.mail_Comp_GenAm, dbo_tblBidder.bidder_number, dbo_tblBidder.bidder_type, dbo_tblMailList.mail_Comp_Art,
dbo_tblMailList.mail_Comp_IndArt, dbo_tblMailList.mail_Comp_Fire, dbo_tblMailList.mail_Comp_Ceramic, dbo_tblSale.sale_id
HAVING (dbo_tblMailList.mail_Comp_GenAm = 1)
If anyone has any ideas, please let me know.
Thanks,
James
EDIT
Using Gareth's FROM clause below I now have:
SELECT dbo_tblMailList.mail_FirstName, dbo_tblMailList.mail_LastName, dbo_tblMailList.mail_Address1, dbo_tblMailList.mail_Address2,
dbo_tblMailList.mail_City, dbo_tblMailList.mail_State, dbo_tblMailList.mail_Zip, dbo_tblMailList.mail_Phone1, dbo_tblMailList.mail_Email1,
dbo_tblMailList.mail_Comp_GenAm, dbo_tblBidder.bidder_number, SUM(dbo_tblItem.item_pr) AS SumOfitem_pr, SUM(dbo_tblItem.item_premium)
AS SumOfitem_premium, dbo_tblBidder.bidder_type, dbo_tblSale.sale_id
FROM (
( dbo_tblMailList
LEFT JOIN dbo_tblBidder
ON dbo_tblMailList.mail_ID = dbo_tblBidder.bidder_mail_id
AND dbo_tblBidder.bidder_sale_id IN (319)
)
LEFT JOIN dbo_tblSale
ON dbo_tblBidder.bidder_sale_id = dbo_tblSale.sale_id
)
LEFT JOIN dbo_tblItem
ON dbo_tblBidder.bidder_sale_id = dbo_tblItem.item_sale_id
AND dbo_tblBidder.bidder_number = dbo_tblItem.item_bidder_number
GROUP BY dbo_tblMailList.mail_FirstName, dbo_tblMailList.mail_LastName, dbo_tblMailList.mail_Address1, dbo_tblMailList.mail_Address2,
dbo_tblMailList.mail_City, dbo_tblMailList.mail_State, dbo_tblMailList.mail_Zip, dbo_tblMailList.mail_Phone1, dbo_tblMailList.mail_Email1,
dbo_tblMailList.mail_Comp_GenAm, dbo_tblBidder.bidder_number, dbo_tblBidder.bidder_type, dbo_tblMailList.mail_Comp_Art,
dbo_tblMailList.mail_Comp_IndArt, dbo_tblMailList.mail_Comp_Fire, dbo_tblMailList.mail_Comp_Ceramic, dbo_tblSale.sale_id
HAVING (dbo_tblMailList.mail_Comp_GenAm = 1)
But I am getting the error Extra ) in query expression ''.
I think it may have something to do with AND dbo_tblBidder.bidder_sale_id IN (319). If I change this to AND dbo_tblBidder.bidder_sale_id = 319, I get the error:
JOIN expression not supported.
And it highlights the dbo_tblBidder.bidder_sale_id = 319.
CONCLUSION
Here is my final working code:
SELECT mail_ID, mail_FirstName, mail_LastName, mail_Address1, mail_Address2,
mail_City, mail_State, mail_Zip, mail_Phone1, mail_Email1,
mail_Comp_GenAm, SUM(SumOfitem_pr) AS SumOfitem_price, SUM(SumOfitem_premium) AS SumOfitem_premiums
FROM (
SELECT dbo_tblMailList.mail_ID, dbo_tblMailList.mail_FirstName, dbo_tblMailList.mail_LastName, dbo_tblMailList.mail_Address1, dbo_tblMailList.mail_Address2,
dbo_tblMailList.mail_City, dbo_tblMailList.mail_State, dbo_tblMailList.mail_Zip, dbo_tblMailList.mail_Phone1, dbo_tblMailList.mail_Email1,
dbo_tblMailList.mail_Comp_GenAm, SUM(dbo_tblItem.item_pr) AS SumOfitem_pr, SUM(dbo_tblItem.item_premium)
AS SumOfitem_premium
FROM (
( dbo_tblMailList
LEFT JOIN dbo_tblBidder
ON dbo_tblMailList.mail_ID = dbo_tblBidder.bidder_mail_id
)
LEFT JOIN dbo_tblSale
ON dbo_tblBidder.bidder_sale_id = dbo_tblSale.sale_id
)
LEFT JOIN dbo_tblItem
ON dbo_tblBidder.bidder_sale_id = dbo_tblItem.item_sale_id
AND dbo_tblBidder.bidder_number = dbo_tblItem.item_bidder_number
WHERE dbo_tblMailList.mail_Comp_GenAm = 1 AND dbo_tblBidder.bidder_sale_id IN (319)
GROUP BY dbo_tblMailList.mail_ID, dbo_tblMailList.mail_FirstName, dbo_tblMailList.mail_LastName, dbo_tblMailList.mail_Address1, dbo_tblMailList.mail_Address2,
dbo_tblMailList.mail_City, dbo_tblMailList.mail_State, dbo_tblMailList.mail_Zip, dbo_tblMailList.mail_Phone1, dbo_tblMailList.mail_Email1,
dbo_tblMailList.mail_Comp_GenAm, dbo_tblMailList.mail_Comp_Art,
dbo_tblMailList.mail_Comp_IndArt, dbo_tblMailList.mail_Comp_Fire, dbo_tblMailList.mail_Comp_Ceramic
UNION
SELECT dbo_tblMailList.mail_ID, dbo_tblMailList.mail_FirstName, dbo_tblMailList.mail_LastName, dbo_tblMailList.mail_Address1, dbo_tblMailList.mail_Address2,
dbo_tblMailList.mail_City, dbo_tblMailList.mail_State, dbo_tblMailList.mail_Zip, dbo_tblMailList.mail_Phone1, dbo_tblMailList.mail_Email1,
dbo_tblMailList.mail_Comp_GenAm, 0 AS SumOfitem_pr, 0
AS SumOfitem_premium
FROM (
( dbo_tblMailList
LEFT JOIN dbo_tblBidder
ON dbo_tblMailList.mail_ID = dbo_tblBidder.bidder_mail_id
)
LEFT JOIN dbo_tblSale
ON dbo_tblBidder.bidder_sale_id = dbo_tblSale.sale_id
)
LEFT JOIN dbo_tblItem
ON dbo_tblBidder.bidder_sale_id = dbo_tblItem.item_sale_id
AND dbo_tblBidder.bidder_number = dbo_tblItem.item_bidder_number
WHERE dbo_tblMailList.mail_Comp_GenAm = 1
GROUP BY dbo_tblMailList.mail_ID, dbo_tblMailList.mail_FirstName, dbo_tblMailList.mail_LastName, dbo_tblMailList.mail_Address1, dbo_tblMailList.mail_Address2,
dbo_tblMailList.mail_City, dbo_tblMailList.mail_State, dbo_tblMailList.mail_Zip, dbo_tblMailList.mail_Phone1, dbo_tblMailList.mail_Email1,
dbo_tblMailList.mail_Comp_GenAm, dbo_tblMailList.mail_Comp_Art,
dbo_tblMailList.mail_Comp_IndArt, dbo_tblMailList.mail_Comp_Fire, dbo_tblMailList.mail_Comp_Ceramic
)
GROUP BY mail_ID, mail_FirstName, mail_LastName, mail_Address1, mail_Address2,
mail_City, mail_State, mail_Zip, mail_Phone1, mail_Email1,
mail_Comp_GenAm, SumOfitem_price, SumOfitem_premiums
Thanks Gareth!
In access you cannot have multiple joins without separating them with parentheses, i.e.
SELECT *
FROM A
INNER JOIN B
ON A.ID = B.AID
INNER JOIN C
ON B.ID = C.BID;
Is not valid, it would need to be:
SELECT *
FROM (A
INNER JOIN B
ON A.ID = B.AID)
INNER JOIN C
ON B.ID = C.BID;
So, your from clause would need to be:
FROM (
( dbo_tblMailList
LEFT JOIN dbo_tblBidder
ON dbo_tblMailList.mail_ID = dbo_tblBidder.bidder_mail_id
AND dbo_tblBidder.bidder_sale_id IN (319)
)
LEFT JOIN dbo_tblSale
ON dbo_tblBidder.bidder_sale_id = dbo_tblSale.sale_id)
AND dbo_tblSale.sale_id IN (319)
)
LEFT JOIN dbo_tblItem
ON dbo_tblBidder.bidder_sale_id = dbo_tblItem.item_sale_id
AND dbo_tblBidder.bidder_number = dbo_tblItem.item_bidder_number
N.B I have removed all the unnecessary parentheses from the joins to reduce the clutter in the query (it is not necessary to enclose every predicate in parentheses), and exaggerated the tab indentations to show clearly where parentheses open and close
EDIT
I forgot, you cannot apply the constant expression in the JOIN clause in Access, you would need to create a subselect,
dbo_tblMailList
LEFT JOIN dbo_tblBidder
ON dbo_tblMailList.mail_ID = dbo_tblBidder.bidder_mail_id
AND dbo_tblBidder.bidder_sale_id IN (319)
You would need to do
dbo_tblMailList AS m
LEFT JOIN (SELECT * FROM dbo_tblBidder WHERE bidder_sale_id IN (319)) AS b
ON m.mail_ID = b.bidder_mail_id
So your full query would be:
SELECT m.mail_FirstName,
m.mail_LastName,
m.mail_Address1,
m.mail_Address2,
m.mail_City,
m.mail_State,
m.mail_Zip,
m.mail_Phone1,
m.mail_Email1,
m.mail_Comp_GenAm,
b.bidder_number,
SUM(i.item_pr) AS SumOfitem_pr,
SUM(i.item_premium) AS SumOfitem_premium,
b.bidder_type,
s.sale_id
FROM (
( dbo_tblMailList AS m
LEFT JOIN
( SELECT bidder_mail_id , bidder_number, bidder_type, bidder_sale_id
FROM dbo_tblBidder
WHERE bidder_sale_id IN (319)
) AS b
ON m.mail_ID = b.bidder_mail_id
)
LEFT JOIN dbo_tblSale AS s
ON b.bidder_sale_id = s.sale_id
)
LEFT JOIN dbo_tblItem AS i
ON b.bidder_sale_id = i.item_sale_id
AND b.bidder_number = i.item_bidder_number
GROUP BY
m.mail_FirstName, m.mail_LastName, m.mail_Address1, m.mail_Address2, m.mail_City, m.mail_State,
m.mail_Zip, m.mail_Phone1, m.mail_Email1, m.mail_Comp_GenAm, b.bidder_number, b.bidder_type, s.sale_id;
(I have used short table aliases to try and condense the code, not a convention you have to follow)

How do you add an item to a Unionized SQL View?

I am working to make an automated report in Crystal Reports which requires me to add in a table to an existing, pre-written view. The view contains a Union operation which is preventing me from using the view as normal. What I have done is manualy add-in the data (about halfway through).
The item required for the report is tblSOPartsUsed.Memo. which i have added into BOTH select queries. In the join between tblCustomerInventory and tblSOPartsUsed the .Memo table only appears in the PartsUsed table, not in the CustomerInventory.
First Select Query Location
tblCustomerInventory.SerialNumber AS ExchangeSerialNumber, **tblSOPartsUsed.Memo AS SOPartsNotes**, tblInvoiceDetail.Taxable AS DetailIsTaxable,
First From Query Location
tblCustomerInventory FULL OUTER JOIN
tblSOPartsUsed INNER JOIN
I have outlined the second Select and From in exactly the same way.
Can someone please shed some light, i've tried EVERYTHING!
The full code is below...
SELECT InvoiceAssemblyPriceBook.Features AS AssemblyFeatures,
tblInvoiceAssemblyDetail.EachQuantity AS AssemblyEachQuantity,
tblInvoiceAssemblyDetail.FKInvoiceDetail AS AssemblyFKInvoiceDetail,
tblInvoiceAssemblyDetail.InvoiceAssemblyDetailKeyID,
tblInvoiceAssemblyDetail.ItemID AS AssemblyItemID,
tblInvoiceAssemblyDetail.ItemDescription AS AssemblyItemDescription,
tblInvoiceAssemblyDetail.PrintOnInvoice AS AssemblyPrintOnInvoice,
tblInvoiceAssemblyDetail.Quantity AS AssemblyQuantity,
tblInvoiceAssemblyDetail.SellingPrice AS AssemblySellingPrice,
tblInvoiceAssemblyDetail.TotalSellingPrice AS AssemblyTotalSellingPrice,
tblInvoiceAssemblyDetail.Type AS AssemblyType,
tblInvoiceAssemblyDetail.UnitOfMeasure AS AssemblyUnitOfMeasure,
tblInvoiceDetail.AssemblyType AS DetailAssemblyType,
tblInvoiceDetail.InvoiceDetailKeyID,
tblInvoiceDetail.ItemDescription AS DetailItemDescription,
tblInvoiceDetail.ItemID AS DetailItemID,
tblInvoiceDetail.PrintOnInvoice AS DetailPrintOnInvoice,
tblInvoiceDetail.Quantity AS DetailQuantity,
tblInvoiceDetail.SellingPrice AS DetailSellingPrice,
tblInvoiceDetail.TotalSellingPrice AS DetailTotalSellingPrice,
tblInvoiceDetail.Type AS DetailType,
tblInvoices.AccountNumber,
tblInvoices.Comments,
tblInvoices.ContractNumber,
tblInvoices.Deposit,
tblInvoices.Freight,
tblInvoices.GSTax,
tblInvoices.InvoiceDate,
tblInvoices.InvoiceNumber,
tblInvoices.PaidDate,
tblInvoices.QuoteNumber,
tblInvoices.SalesTaxPercent,
CASE
WHEN tblInvoiceDetail.SoNumber IS NULL
THEN tblInvoices.SONumber
ELSE tblInvoiceDetail.SoNumber
END AS SONumber,
tblInvoices.STATUS,
tblInvoices.StatusDate,
tblInvoices.Tax,
tblInvoices.TotalAmountDue,
tblInvoices.TotalComment,
tblInvoices.TotalDollarsDiscounted,
tblInvoices.TotalGrossSell,
tblInvoices.TotalNetSell,
tblInvoices.TradeIn,
tblInvoices.WorkOrderNumber,
tblPriceLevels.IsRepairLevel,
tblServiceOrders.ContractNumber AS ServiceOrderContractNumber,
tblSysCompanySettings.HideGSTaxRelatedInformation,
tblSysCompanySettings.ItemsServicedPrintOnInvoice,
tblSysDisclaimerSettings.SalesInvoiceDisclaimer,
tblSysDisclaimerSettings.ServiceInvoiceDisclaimer,
tblSysPBSettings.PrintItemorPartNum,
VoidedByReps.RepName AS VoidedByRepName,
tblInvoices.TotalNetInvoice,
InvoiceDetailPriceBook.PartNumber AS DetailPartNumber,
InvoiceDetailPriceBook.UnitOfMeasure AS DetailUnitOfMeasure,
InvoiceDetailPriceBook.Features AS DetailFeatures,
tblSysDisclaimerSettings.ContractInvoiceDisclaimer,
tblInvoices.ProviderTax,
tblServiceOrders.BriefDescription AS SOBriefDescription,
tblInvoices.GSTaxComputedBeforeTradeIn,
tblInvoices.TaxComputedBeforeTradeIn,
tblInvoices.ProviderTaxRate,
tblInvoices.FreightTaxable,
tblInvoices.GSTIsTaxable,
tblInvoices.ProjectKeyID,
InvoicesReps.RepName,
tblAccounts.AccountNumber AS Expr1,
tblAccounts.AccountID,
tblInvoices.Terms,
tblInvoices.Reference,
tblInvoices.ARCustomerNumber,
tblInvoices.PONumber,
tblInvoices.ShipVia,
tblServiceOrders.DateRequested,
tblServiceOrders.DateOpened,
tblServiceOrders.SONumber AS ServiceOrderSONumber,
tblSysReportSettings.InvoiceCommentsAtEnd,
tblInvoices.SourceDocument,
tblTaxCodes.HasTieredDistrict,
tblExchange.ExchangeKeyID,
tblCustomerInventory.ItemID AS ExchangeItemID,
tblCustomerInventory.ItemDescription AS ExchangeItemDescription,
tblCustomerInventory.SerialNumber AS ExchangeSerialNumber,
tblSOPartsUsed.Memo AS SOPartsNotes,
tblInvoiceDetail.Taxable AS DetailIsTaxable,
tblInvoiceAssemblyDetail.Taxable AS AssemblyIsTaxable,
tblInvoices.IsFinalProgressiveInvoice,
tblInvoiceDetail.IsProgressiveInvoiceItem,
tblInvoices.IsProgressiveInvoice,
tblInvoices.TotalPriceCredited,
tblInvoices.TotalTaxCredited,
tblInvoices.TotalGSTaxCredited,
tblInvoices.TotalProviderTaxCredited,
tblInvoices.TotalFreightCredited,
tblInvoices.DiscountAllowed,
tblInvoices.AmountPaid,
(
SELECT MAX(SOItemsServicedKeyID) AS Expr1
FROM tblSOItemsServiced
WHERE (SONumber = tblServiceOrders.SONumber)
) AS SOItemsServicedKeyID,
tblInvoiceDetail.CommentOnly,
ServiceOrderContacts.ContactName AS SOContactName,
tblServiceOrders.ContactPhone AS SOContactPhone,
tblServiceOrders.ContactPhoneLocation AS SOContactPhoneLocation,
(
SELECT TOP (1) FormattedPhoneNumber
FROM tblPhoneNumbers
WHERE (ContactNumber = 0)
AND (PrimaryIndicator = 1)
AND (COALESCE(PhoneLocation, '') <> 'Fax')
AND (AccountNumber = tblAccounts.AccountNumber)
) AS AccountPhone,
(
SELECT TOP (1) PhoneLocation
FROM tblPhoneNumbers AS tblPhoneNumbers_1
WHERE (ContactNumber = 0)
AND (PrimaryIndicator = 1)
AND (COALESCE(PhoneLocation, '') <> 'Fax')
AND (AccountNumber = tblAccounts.AccountNumber)
) AS AccountPhoneLocation,
COALESCE(tvwr_TotalAmountDuePerAccount.AmountDue, 0.00) AS AmountDue,
COALESCE(tvwr_TotalAmountDuePerAccount.Unappliedpayments, 0.00) AS Unappliedpayments,
tblTaxCodes.IsHarmonizedTaxCode,
tblInvoices.GSTax + tblInvoices.Tax AS HSTax
FROM tblPriceBook AS InvoiceAssemblyPriceBook
RIGHT JOIN tblPriceBook AS InvoiceDetailPriceBook
RIGHT JOIN tblInvoiceAssemblyDetail
RIGHT JOIN tblCustomerInventory
FULL JOIN tblSOPartsUsed
INNER JOIN tblExchange
ON tblSOPartsUsed.SOPartsUsedKeyID = tblExchange.FKSOPartsUsed
ON tblCustomerInventory.CustomerInventoryKeyID = tblExchange.FKCustomerInventory RIGHT JOIN tblInvoiceDetail
ON tblSOPartsUsed.FKInvoiceDetail = tblInvoiceDetail.InvoiceDetailKeyID
ON tblInvoiceAssemblyDetail.FKInvoiceDetail = tblInvoiceDetail.InvoiceDetailKeyID
ON InvoiceDetailPriceBook.ItemID = tblInvoiceDetail.ItemID
ON InvoiceAssemblyPriceBook.ItemID = tblInvoiceAssemblyDetail.ItemID LEFT JOIN tblPriceLevels
ON tblInvoiceDetail.PriceLevel = tblPriceLevels.PriceLevelsKeyID RIGHT JOIN tvwr_TotalAmountDuePerAccount INNER JOIN tblAccounts
ON tvwr_TotalAmountDuePerAccount.AccountNumber = tblAccounts.AccountNumber RIGHT JOIN tblReps AS VoidedByReps RIGHT JOIN tblInvoices AS tblInvoices LEFT JOIN tblTaxCodes
ON tblInvoices.SalesTaxCode = tblTaxCodes.SalesTaxCode LEFT JOIN tblReps AS InvoicesReps
ON tblInvoices.SalesRep = InvoicesReps.RepNumber
ON VoidedByReps.RepNumber = tblInvoices.StatusBy LEFT JOIN tblServiceOrders LEFT JOIN tblContacts AS ServiceOrderContacts
ON tblServiceOrders.ContactNumber = ServiceOrderContacts.ContactNumber
ON tblInvoices.SONumber = tblServiceOrders.SONumber
ON tblAccounts.AccountNumber = tblInvoices.AccountNumber
ON tblInvoiceDetail.InvoiceNumber = tblInvoices.InvoiceNumber LEFT JOIN tblContacts AS tblContacts
ON tblAccounts.PrimaryContactNumber = tblContacts.ContactNumber CROSS JOIN tblSysPBSettings CROSS JOIN tblSysCompanySettings CROSS JOIN tblSysReportSettings CROSS JOIN tblSysDisclaimerSettings
WHERE (tblInvoices.MSPAgreementNumber = 0)
UNION ALL
SELECT InvoiceAssemblyPriceBook.Features AS AssemblyFeatures,
tblInvoiceAssemblyDetail.EachQuantity AS AssemblyEachQuantity,
tblInvoiceAssemblyDetail.FKInvoiceDetail AS AssemblyFKInvoiceDetail,
tblInvoiceAssemblyDetail.InvoiceAssemblyDetailKeyID,
tblInvoiceAssemblyDetail.ItemID AS AssemblyItemID,
tblInvoiceAssemblyDetail.ItemDescription AS AssemblyItemDescription,
tblInvoiceAssemblyDetail.PrintOnInvoice AS AssemblyPrintOnInvoice,
tblInvoiceAssemblyDetail.Quantity AS AssemblyQuantity,
tblInvoiceAssemblyDetail.SellingPrice AS AssemblySellingPrice,
tblInvoiceAssemblyDetail.TotalSellingPrice AS AssemblyTotalSellingPrice,
tblInvoiceAssemblyDetail.Type AS AssemblyType,
tblInvoiceAssemblyDetail.UnitOfMeasure AS AssemblyUnitOfMeasure,
tblInvoiceDetail.AssemblyType AS DetailAssemblyType,
tblInvoiceDetail.InvoiceDetailKeyID,
tblInvoiceDetail.ItemDescription AS DetailItemDescription,
tblInvoiceDetail.ItemID AS DetailItemID,
tblInvoiceDetail.PrintOnInvoice AS DetailPrintOnInvoice,
tblInvoiceDetail.Quantity AS DetailQuantity,
tblInvoiceDetail.SellingPrice AS DetailSellingPrice,
tblInvoiceDetail.TotalSellingPrice AS DetailTotalSellingPrice,
tblInvoiceDetail.Type AS DetailType,
tblInvoices.AccountNumber,
tblInvoices.Comments,
tblInvoices.ContractNumber,
tblInvoices.Deposit,
tblInvoices.Freight,
tblInvoices.GSTax,
tblInvoices.InvoiceDate,
tblInvoices.InvoiceNumber,
tblInvoices.PaidDate,
tblInvoices.QuoteNumber,
tblInvoices.SalesTaxPercent,
CASE
WHEN tblInvoiceDetail.SoNumber IS NULL
THEN tblInvoices.SONumber
ELSE tblInvoiceDetail.SoNumber
END AS SONumber,
tblInvoices.STATUS,
tblInvoices.StatusDate,
tblInvoices.Tax,
tblInvoices.TotalAmountDue,
tblInvoices.TotalComment,
tblInvoices.TotalDollarsDiscounted,
tblInvoices.TotalGrossSell,
tblInvoices.TotalNetSell,
tblInvoices.TradeIn,
tblInvoices.WorkOrderNumber,
tblPriceLevels.IsRepairLevel,
tblServiceOrders.ContractNumber AS ServiceOrderContractNumber,
tblSysCompanySettings.HideGSTaxRelatedInformation,
tblSysCompanySettings.ItemsServicedPrintOnInvoice,
tblSysDisclaimerSettings.SalesInvoiceDisclaimer,
tblSysDisclaimerSettings.MSPAgreementInvoiceDisclaimer AS ServiceInvoiceDisclaimer,
tblSysPBSettings.PrintItemorPartNum,
VoidedByReps.RepName AS VoidedByRepName,
tblInvoices.TotalNetInvoice,
InvoiceDetailPriceBook.PartNumber AS DetailPartNumber,
InvoiceDetailPriceBook.UnitOfMeasure AS DetailUnitOfMeasure,
InvoiceDetailPriceBook.Features AS DetailFeatures,
tblSysDisclaimerSettings.ContractInvoiceDisclaimer,
tblInvoices.ProviderTax,
tblServiceOrders.BriefDescription AS SOBriefDescription,
tblInvoices.GSTaxComputedBeforeTradeIn,
tblInvoices.TaxComputedBeforeTradeIn,
tblInvoices.ProviderTaxRate,
tblInvoices.FreightTaxable,
tblInvoices.GSTIsTaxable,
tblInvoices.ProjectKeyID,
InvoicesReps.RepName,
tblAccounts.AccountNumber AS Expr1,
tblAccounts.AccountID,
tblInvoices.Terms,
tblInvoices.Reference,
tblInvoices.ARCustomerNumber,
tblInvoices.PONumber,
tblInvoices.ShipVia,
tblServiceOrders.DateRequested,
tblServiceOrders.DateOpened,
tblServiceOrders.SONumber AS ServiceOrderSONumber,
tblSysReportSettings.InvoiceCommentsAtEnd,
tblInvoices.SourceDocument,
tblTaxCodes.HasTieredDistrict,
tblExchange.ExchangeKeyID,
tblCustomerInventory.ItemID AS ExchangeItemID,
tblCustomerInventory.ItemDescription AS ExchangeItemDescription,
tblCustomerInventory.SerialNumber AS ExchangeSerialNumber,
tblSOPartsUsed.Memo AS SOPartsNotes,
tblInvoiceDetail.Taxable AS DetailIsTaxable,
tblInvoiceAssemblyDetail.Taxable AS AssemblyIsTaxable,
tblInvoices.IsFinalProgressiveInvoice,
tblInvoiceDetail.IsProgressiveInvoiceItem,
tblInvoices.IsProgressiveInvoice,
tblInvoices.TotalPriceCredited,
tblInvoices.TotalTaxCredited,
tblInvoices.TotalGSTaxCredited,
tblInvoices.TotalProviderTaxCredited,
tblInvoices.TotalFreightCredited,
tblInvoices.DiscountAllowed,
tblInvoices.AmountPaid,
(
SELECT MAX(SOItemsServicedKeyID) AS Expr1
FROM tblSOItemsServiced
WHERE (SONumber = tblServiceOrders.SONumber)
) AS SOItemsServicedKeyID,
tblInvoiceDetail.CommentOnly,
ServiceOrderContacts.ContactName AS SOContactName,
tblServiceOrders.ContactPhone AS SOContactPhone,
tblServiceOrders.ContactPhoneLocation AS SOContactPhoneLocation,
(
SELECT TOP (1) FormattedPhoneNumber
FROM tblPhoneNumbers
WHERE (ContactNumber = 0)
AND (PrimaryIndicator = 1)
AND (COALESCE(PhoneLocation, '') <> 'Fax')
AND (AccountNumber = tblAccounts.AccountNumber)
) AS AccountPhone,
(
SELECT TOP (1) PhoneLocation
FROM tblPhoneNumbers AS tblPhoneNumbers_1
WHERE (ContactNumber = 0)
AND (PrimaryIndicator = 1)
AND (COALESCE(PhoneLocation, '') <> 'Fax')
AND (AccountNumber = tblAccounts.AccountNumber)
) AS AccountPhoneLocation,
COALESCE(tvwr_TotalAmountDuePerAccount.AmountDue, 0.00) AS AmountDue,
COALESCE(tvwr_TotalAmountDuePerAccount.Unappliedpayments, 0.00) AS Unappliedpayments,
COALESCE(tblTaxCodes.IsHarmonizedTaxCode, 0) AS IsHarmonizedTaxCode,
tblInvoices.GSTax + tblInvoices.Tax AS HSTax
FROM tblPriceBook AS InvoiceAssemblyPriceBook
RIGHT JOIN tblPriceBook AS InvoiceDetailPriceBook
RIGHT JOIN tblInvoiceAssemblyDetail
RIGHT JOIN tblCustomerInventory
FULL JOIN tblSOPartsUsed
INNER JOIN tblExchange
ON tblSOPartsUsed.SOPartsUsedKeyID = tblExchange.FKSOPartsUsed
ON tblCustomerInventory.CustomerInventoryKeyID = tblExchange.FKCustomerInventory RIGHT JOIN tblInvoiceDetail
ON tblSOPartsUsed.FKInvoiceDetail = tblInvoiceDetail.InvoiceDetailKeyID
ON tblInvoiceAssemblyDetail.FKInvoiceDetail = tblInvoiceDetail.InvoiceDetailKeyID
ON InvoiceDetailPriceBook.ItemID = tblInvoiceDetail.ItemID
ON InvoiceAssemblyPriceBook.ItemID = tblInvoiceAssemblyDetail.ItemID LEFT JOIN tblPriceLevels
ON tblInvoiceDetail.PriceLevel = tblPriceLevels.PriceLevelsKeyID RIGHT JOIN tvwr_TotalAmountDuePerAccount INNER JOIN tblAccounts
ON tvwr_TotalAmountDuePerAccount.AccountNumber = tblAccounts.AccountNumber RIGHT JOIN tblReps AS VoidedByReps RIGHT JOIN tblInvoices AS tblInvoices LEFT JOIN tblTaxCodes
ON tblInvoices.SalesTaxCode = tblTaxCodes.SalesTaxCode LEFT JOIN tblReps AS InvoicesReps
ON tblInvoices.SalesRep = InvoicesReps.RepNumber
ON VoidedByReps.RepNumber = tblInvoices.StatusBy LEFT JOIN tblServiceOrders LEFT JOIN tblContacts AS ServiceOrderContacts
ON tblServiceOrders.ContactNumber = ServiceOrderContacts.ContactNumber
ON tblInvoices.SONumber = tblServiceOrders.SONumber
ON tblAccounts.AccountNumber = tblInvoices.AccountNumber
ON tblInvoiceDetail.InvoiceNumber = tblInvoices.InvoiceNumber LEFT JOIN tblContacts AS tblContacts
ON tblAccounts.PrimaryContactNumber = tblContacts.ContactNumber CROSS JOIN tblSysPBSettings CROSS JOIN tblSysCompanySettings CROSS JOIN tblSysReportSettings CROSS JOIN tblSysDisclaimerSettings
WHERE (tblInvoices.MSPAgreementNumber <> 0)
I managed to copy each half of the view into a new view, manually tick off the tblSOPartsUsed.memo from the GUI and copied the two together which made the view work great