这应该被允许 - 我不明白为什么不是。
SELECT *
FROM (
SELECT *
FROM MyTable
)
答案 0 :(得分:10)
在SQL Server中允许使用,但必须为内部选择指定名称,例如:
SELECT *
FROM (
SELECT *
FROM MyTable
) m
如果未提供名称,则会在')'消息附近引发错误的语法错误。
答案 1 :(得分:6)
如果你添加一个表别名,它应该可以工作:
SELECT *
FROM (
SELECT *
FROM MyTable
) as A
答案 2 :(得分:4)
您在子查询中缺少'别名' (我添加了一个别名'X')
SELECT *
FROM (
SELECT *
FROM MyTable
) X
答案 3 :(得分:2)
至少有两种方法可以实现这一点,但您可能正在寻找的是SQL Server 2005中引入的Common Table Expression (CTE)。
从以上链接:
USE AdventureWorks;
GO
WITH Sales_CTE (SalesPersonID, NumberOfOrders, MaxDate)
AS
(
SELECT SalesPersonID, COUNT(*), MAX(OrderDate)
FROM Sales.SalesOrderHeader
GROUP BY SalesPersonID
)
SELECT E.EmployeeID, OS.NumberOfOrders, OS.MaxDate,
E.ManagerID, OM.NumberOfOrders, OM.MaxDate
FROM HumanResources.Employee AS E
JOIN Sales_CTE AS OS
ON E.EmployeeID = OS.SalesPersonID
LEFT OUTER JOIN Sales_CTE AS OM
ON E.ManagerID = OM.SalesPersonID
ORDER BY E.EmployeeID;
GO
或者,您可以创建一个View,它是您可以按名称访问的查询的永久表格形式:
USE AdventureWorks ;
GO
IF OBJECT_ID ('hiredate_view', 'V') IS NOT NULL
DROP VIEW hiredate_view ;
GO
CREATE VIEW hiredate_view
AS
SELECT c.FirstName, c.LastName, e.EmployeeID, e.HireDate
FROM HumanResources.Employee e JOIN Person.Contact c on e.ContactID = c.ContactID ;
GO
SELECT * FROM hiredate_view