以下查询将生成20行。我正在尝试消除“类型和版本”的重复版本,但我一直在返回重复的
SELECT DISTINCT
STR(C.CustomerID, 4) AS 'Customer ID',
STR(INV.InvoiceNbr, 3) AS 'Invoice Number',
STR(LINE.FK_StoveNbr, 3) AS 'Stove Number',
CAST(S.Type + ', ' + S.Version AS CHAR (15)) AS 'Type and Version'
FROM CUSTOMER C, INVOICE INV, INV_LINE_ITEM LINE, STOVE S
WHERE INV.FK_CustomerID = C.CustomerID
AND INV.InvoiceNbr = LINE.FK_InvoiceNbr
AND SerialNumber = LINE.FK_StoveNbr
AND C.StateProvince = 'OR'
ORDER BY 'Type and Version';
无论如何,我在结果中不断获得Stove Type和Version的多个版本。我不确定这是对的,因为俄勒冈州只有十个客户。
答案 0 :(得分:0)
您使用直接连接,请尝试切换到左侧。
SELECT DISTINCT
STR(C.CustomerID, 4) AS 'Customer ID',
STR(INV.InvoiceNbr, 3) AS 'Invoice Number',
STR(LINE.FK_StoveNbr, 3) AS 'Stove Number',
CAST(S.Type + ', ' + S.Version AS CHAR (15)) AS 'Type and Version'
FROM INVOICE INV,
LEFT JOIN CUSTOMER C on (C.CustomerID = INV.FK_CustomerID)
LEFT JOIN INV_LINE_ITEM LINE ON (INV.InvoiceNbr = LINE.FK_InvoiceNbr)
LEFT JOIN STOVE S ON (S.SerialNumber = LINE.FK_StoveNbr)
WHERE C.StateProvince = 'OR'
ORDER BY 'Type and Version';
原因是Straight join将所有表视为主表。 1 = 1,左连接可让您设置优先级。所以在我的例子中。 INVOICE是主要表格。所有其他表仅用于填写额外信息。他们是附加的。
希望这是有道理的。