SQL 加入视图 - 重复字段

SQL Join Views - Duplicate Field

我正在尝试加入两个视图,我已尝试将 StkSalesUpdated 视图下的 cAuditNumber 字段别名为 AuditNumber1,但我仍然收到以下消息:

Msg 4506, Level 16, State 1, Procedure KFF_Sales_Data_Updated, Line 3 Column names in each view or function must be unique. Column name 'cAuditNumber' in view or function 'KFF_Sales_Data_Updated' is specified more than once.

下面是我的SQL声明:

CREATE VIEW KFF_Sales_Data_Updated
AS
SELECT CustSalesUpdated.cAuditNumber
   ,CustSalesUpdated.Account
   ,CustSalesUpdated.cAuditNumber
   ,CustSalesUpdated.Name
   ,StkSalesUpdated.cAuditNumber as AuditNumber1
   ,StkSalesUpdated.Code
   ,StkSalesUpdated.Credit
   ,StkSalesUpdated.Debit
   ,StkSalesUpdated.Description_1
   ,StkSalesUpdated.Id
   ,StkSalesUpdated.ItemGroup
   ,StkSalesUpdated.Quantity
   ,StkSalesUpdated.Reference
   ,StkSalesUpdated.TxDate
FROM CustSalesUpdated
INNER JOIN StkSalesUpdated
ON StkSalesUpdated.cAuditNumber = CustSalesUpdated.cAuditNumber

您在位置 1 和位置 3 有两个 cauditnumber 实例,您需要别名或删除一个。

CREATE VIEW KFF_Sales_Data_Updated
AS
SELECT CustSalesUpdated.cAuditNumber -- HERE
   ,CustSalesUpdated.Account
   ,CustSalesUpdated.cAuditNumber --HERE
   ,CustSalesUpdated.Name
   ,StkSalesUpdated.cAuditNumber as AuditNumber1
   ,StkSalesUpdated.Code
   ,StkSalesUpdated.Credit
   ,StkSalesUpdated.Debit
   ,StkSalesUpdated.Description_1
   ,StkSalesUpdated.Id
   ,StkSalesUpdated.ItemGroup
   ,StkSalesUpdated.Quantity
   ,StkSalesUpdated.Reference
   ,StkSalesUpdated.TxDate
FROM CustSalesUpdated
INNER JOIN StkSalesUpdated
ON StkSalesUpdated.cAuditNumber = CustSalesUpdated.cAuditNumber

也许这不是因为您重命名或加入,而是因为您 select 它来自同一个 table 两次? (select 语句的前 3 行)

SELECT CustSalesUpdated.cAuditNumber  
,CustSalesUpdated.Account
,CustSalesUpdated.cAuditNumber

在 SELECT 列表中多次指定了相同的列名。为其他人提供备用名称将解决您的问题。

CREATE VIEW KFF_Sales_Data_Updated
    AS
    SELECT CustSalesUpdated.cAuditNumber
       ,CustSalesUpdated.Account
       ,CustSalesUpdated.cAuditNumber as cAuditNumber_2
       ,CustSalesUpdated.Name
       ,StkSalesUpdated.cAuditNumber as AuditNumber1
       ,StkSalesUpdated.Code
       ,StkSalesUpdated.Credit
       ,StkSalesUpdated.Debit
       ,StkSalesUpdated.Description_1
       ,StkSalesUpdated.Id
       ,StkSalesUpdated.ItemGroup
       ,StkSalesUpdated.Quantity
       ,StkSalesUpdated.Reference
       ,StkSalesUpdated.TxDate
    FROM CustSalesUpdated
    INNER JOIN StkSalesUpdated
    ON StkSalesUpdated.cAuditNumber = CustSalesUpdated.cAuditNumber