使用SQL Server,我有Where子句的兩個Select語句,但不斷得到重複的結果。我的第一個查詢是:SQL合併兩個選擇具有不同列號的查詢,同時刪除重複項?
SELECT
PricingContingencies.*,
Terms.*,
rscDescription AS RateScheme,
ptyAbbreviation AS PointTypeAbbreviation,
FAKs.*,
fat.*
FROM ((((PricingContingencies
INNER JOIN Terms ON pcoTerms = terID)
INNER JOIN PointTypes ON pcoPointTypeFK = ptyID)
LEFT JOIN RateSchemes ON pcoRateSchemeFK = rscID)
LEFT JOIN FAKs ON fakPricingContingencyFK = pcoID)
LEFT JOIN FuelAgreementTypes fat ON ftyID = pcoFuelAgreementTypeFK
WHERE pcoPricingAgreementFK = 61523 and pcoID = 16490608
並返回兩行(這是正確的)。
我的第二個查詢非常相似,但有附加列(唯一的區別是 'LEFT JOIN PalletPricing ON pprPricingContingenciesFK = pcoID)' 而不是 'LEFT JOIN電傳ON fakPricingContingencyFK = pcoID)':
SELECT
PricingContingencies.*,
Terms.*,
rscDescription as RateScheme,
ptyAbbreviation as PointTypeAbbreviation,
PalletPricing.*,
fat.*
FROM ((((PricingContingencies
INNER JOIN Terms ON pcoTerms = terID)
INNER JOIN PointTypes ON pcoPointTypeFK = ptyID)
LEFT JOIN RateSchemes ON pcoRateSchemeFK = rscID)
LEFT JOIN PalletPricing ON pprPricingContingenciesFK = pcoID)
LEFT JOIN FuelAgreementTypes fat ON ftyID = pcoFuelAgreementTypeFK
WHERE pcoPricingAgreementFK = 61523 and pcoID = 16490608
而且返回6行(這也是正確的)。
我該如何合併它們才能獲得8行總計?如果我使用將它們組合起來的INNER JOIN像:
SELECT
FirstSet.*,
SecondSet.*
FROM (
SELECT
PricingContingencies.*,
Terms.*,
rscDescription AS RateScheme,
ptyAbbreviation AS PointTypeAbbreviation,
FAKs.*,
fat.*
FROM ((((PricingContingencies
INNER JOIN Terms ON pcoTerms = terID)
INNER JOIN PointTypes ON pcoPointTypeFK = ptyID)
LEFT JOIN RateSchemes ON pcoRateSchemeFK = rscID)
LEFT JOIN FAKs ON fakPricingContingencyFK = pcoID)
LEFT JOIN FuelAgreementTypes fat ON ftyID = pcoFuelAgreementTypeFK
WHERE pcoPricingAgreementFK = 61523 and pcoID = 16490608
) as FirstSet
INNER JOIN
(
SELECT
PricingContingencies.*,
Terms.*,
rscDescription as RateScheme,
ptyAbbreviation as PointTypeAbbreviation,
PalletPricing.*,
fat.*
FROM ((((PricingContingencies
INNER JOIN Terms ON pcoTerms = terID)
INNER JOIN PointTypes ON pcoPointTypeFK = ptyID)
LEFT JOIN RateSchemes ON pcoRateSchemeFK = rscID)
LEFT JOIN PalletPricing ON pprPricingContingenciesFK = pcoID)
LEFT JOIN FuelAgreementTypes fat ON ftyID = pcoFuelAgreementTypeFK
WHERE pcoPricingAgreementFK = 61523 and pcoID = 16490608
) as SecondSet
ON FirstSet.pcoID = SecondSet.pcoID
ORDER BY FirstSet.pcoPriority DESC
我得到12行,其中PalletPricing列被複制和不正確(第二結果加倍[6×2])。我如何組合它們,以便得到正確的8行(2 + 6)?
在此先感謝。
你基本上是在尋找一個UNION查詢。但是,UNION(或其更具包容性的同級UNION ALL)要求兩個查詢的列數完全相同,並且每列中的數據類型大致相同。除非PalletPricing和Fak具有相同的表格佈局,否則您必須在某些時候返回假數據,並且將兩個來源中的每個來源的列名設置爲您從頂級查詢輸出的任何列名稱。 –
他們真的是重複的嗎?可能至少有一列不同。 – Parfait
你是對的,一列是不同的。如何排除一個不同的列,以便整個行不包含在查詢中? – smac