创建VIEW以替换嵌套的SELECT,无法正常工作

时间:2014-10-30 18:39:43

标签: sql-server view

SQL Server 2012

这是一个有效的嵌套SELECT语句

SELECT DISTINCT Computer_Name, IP_Address, COUNT(Computer_ID) AS Num_Computer_ID
FROM dbo.Computers
WHERE Computer_Name in (SELECT DISTINCT Computer_Name
                        FROM dbo.Computers
                        WHERE dbo.Computers.COMPUTER_NAME LIKE '%s001'
                        AND dbo.Computers.IP_Address LIKE '%.100'
                        GROUP BY Computer_Name,IP_Address
                        HAVING COUNT(DISTINCT Computer_ID) > 1)
AND dbo.Computers.COMPUTER_NAME LIKE '%s001'
AND dbo.Computers.IP_Address LIKE '%.100'
GROUP BY Computer_Name, IP_Address
ORDER BY Num_Computer_ID DESC

我创建了一个VIEW以避免嵌套SELECT语句

CREATE VIEW V_Duplicate_ID 
AS SELECT DISTINCT Computer_Name
FROM dbo.Computers
WHERE dbo.Computers.COMPUTER_NAME LIKE '%s001'
AND dbo.Computers.IP_Address LIKE '%.100'
GROUP BY Computer_Name,IP_Address
HAVING COUNT(DISTINCT Computer_ID) > 1;

当我运行SELECT * FROM V_Duplicate_ID时,它可以工作,但当我合并视图以替换嵌套的SELECT语句时

SELECT DISTINCT Computer_Name, IP_Address, COUNT(Computer_ID) AS Num_Computer_ID
FROM dbo.Computers, [V_Duplicate_ID]
WHERE dbo.Computers.Computer_Name = [dbo].[V_Duplicate_ID].Computer_Name
AND dbo.Computers.COMPUTER_NAME LIKE '%s001'
AND dbo.Computers.IP_Address LIKE '%.100'
GROUP BY Computer_Name, IP_Address
ORDER BY Num_Computer_ID DESC

我收到错误

Msg 209, Level 16, State 1, Line 6
Ambiguous column name 'Computer_Name'.
Msg 209, Level 16, State 1, Line 1
Ambiguous column name 'Computer_Name'.

如何解决?

1 个答案:

答案 0 :(得分:1)

使用以下选择查询,在SELECT和GROUP BY关键字中简单地将 dbo.Computers 放在Computer_Name的前面。

因为在创建视图时,它还具有列名Computer_name。所以存在冲突。但是当你在查询之前执行时,列名将是 DISTINCT(Computer_Name)

SELECT DISTINCT **dbo.Computers.Computer_Name**,  
IP_Address, COUNT(Computer_ID) AS Num_Computer_ID  
FROM dbo.Computers, [V_Duplicate_ID]  
WHERE dbo.Computers.Computer_Name = [dbo].[V_Duplicate_ID].Computer_Name  
AND dbo.Computers.COMPUTER_NAME LIKE '%s001'  
AND dbo.Computers.IP_Address LIKE '%.100'  
GROUP BY **dbo.Computers.Computer_Name**, IP_Address  
ORDER BY Num_Computer_ID DESC