是否可以封装sql-select结果?

时间:2014-04-26 20:18:15

标签: sql sql-server select

简单SQL查询:

(select e.lastName as Name, count(o.orderid) as numOrd from
Employees e join Orders o on e.employeeid=o.employeeid
group by e.lastName)

和结果

布坎南42
卡拉汉104
达沃利奥123
Dodsworth 43

我的问题是如何在SQL中实现类似的东西:

let queryResult = 
(select e.lastName as Name, count(o.orderid) as numOrd from
Employees e join Orders o on e.employeeid=o.employeeid
group by e.lastName)

然后写下这样的东西,这将是输出:

select AVG(qr.numOrd) from queryResult qr

是否可以不创建任何新表?

3 个答案:

答案 0 :(得分:2)

是的,但为什么不是这样的:

select count(o.orderid) / count (distinct e.employeeid) AvgNumOrder
  from orders

派生表,CTE,子查询,临时表,表变量都按照您的要求执行,但不需要任何操作。

答案 1 :(得分:0)

您可能想要使用a Common Table Expression (CTE)

答案 2 :(得分:0)

查看SQL Server Views

您可以将视图定义为

create view queryResult as
select e.lastName as Name, count(o.orderid) as numOrd from
Employees e join Orders o on e.employeeid=o.employeeid
group by e.lastName;