使用派生表来计算聚合或使用连接是否更好?在下面的示例中,派生表是整个查询,但性能明智更快? **我没有查询计划,也看不出支出差异** **
SELECT
sl_ytd.state,
sl_ytd.num_stores,
sl_ytd.ytd_sales
FROM
(SELECT
SUM(sis.sales_dollars_ytd) as ytd_sales,
COUNT(DISTINCT s.store_key) as num_stores,
s.state
FROM snapshot_item_store sis
JOIN stores s on s.store_key = sis.store_key
GROUP BY
s.state) sl_ytd
答案 0 :(得分:1)
如果通过仅引用子表来计算派生表中的聚合,则"组按"可以对外键上的非聚集索引进行操作。如果您改为执行连接,然后针对所有返回列计算聚合,则必须生成临时表并执行大量额外工作。
SELECT
c.CompanyName,
ISNULL(cu.UserCount, 0) AS UserCount
FROM
Company c
LEFT OUTER JOIN
(
SELECT
u.CompanyID,
COUNT(*) AS UserCount
FROM
[User] u
GROUP BY
u.CompanyID
) cu ON
cu.CompanyID = c.CompanyID
ORDER BY
c.CompanyName;
VS
SELECT
c.CompanyName,
ISNULL(COUNT(u.CompanyID), 0) AS UserCount
FROM
Company c
LEFT OUTER JOIN [User] u ON
u.CompanyID = c.CompanyID
GROUP BY
c.CompanyID
ORDER BY
c.CompanyName;