我的工作是运行 SQL Server 2008,并且我花费大量时间查询数据库以获取信息,作为我工作的一部分。如果我需要与我的数据集不在同一聚合级别的信息,我会在 select 语句中使用嵌入式查询。通常是相同数字的 2 或 3 个略有不同的版本,因此它们都查询相同的表。(见下面的例子)
问题是嵌入在 select 语句中的子查询的别名的范围是什么。我想到的两个选择是:
- 在脚本级别并且必须对所有子查询和表都是唯一的?
- 在子查询级别,并且可以在每个中共享相同的别名。
我知道对于 From 语句中别名的表,它们必须是唯一的。我认为查询在每一行生成上执行的事实可能是不同的情况。
示例(完全编造,让我知道任何明显的错误,我会纠正它们):
脚本级别 - 所有子查询和表的唯一别名:
Select
p.purchaseid, p.purchasedate,
s.storename, c.customerid,
(select count(p2.purchaseid)
from purchases p2 inner join
store s2 on p2.storeid = s2.storeid
where s2.storeid = s.storeid
and p2.purchasedate = p.purchasedate) as 'Store Daily Total Purchases',
(select count(p3.purchaseid)
from purchases p3 inner join
store s3 on p3.storeid = s3.storeid
where p3.customerid = p.customerid
and p3.purchasedate = p.purchasedate) as 'Customer Daily Total Purchases'
from
purchases p inner join
customer c on p.customerid = c.customerid
store s on p.storeid = s.storeid
查询级别 - 子查询的常用别名可以:
Select
p.purchaseid, p.purchasedate,
s.storename, c.customerid,
(select count(p2.purchaseid)
from purchases p2 inner join
store s2 on p2.storeid = s2.storeid
where s2.storeid = s.storeid
and p2.purchasedate = p.purchasedate) as 'Store Daily Total Purchases',
(select count(p2.purchaseid)
from purchases p2 inner join
store s2 on p2.storeid = s2.storeid
where p2.customerid = p.customerid
and p2.purchasedate = p.purchasedate) as 'Customer Daily Total Purchases'
from
purchases p inner join
customer c on p.customerid = c.customerid
store s on p.storeid = s.storeid