使用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