在SQL Server中,我不能多次引用WITH
表达式?
DECLARE @total FLOAT;
WITH cte AS (
SELECT s.plate, SUM(s.net) AS tonnage
FROM scale s
GROUP BY s.plate
)
SELECT @total = SUM(tonnage) / 100 FROM cte;
SELECT t.*, t.tonnage / @total AS percentage FROM cte t;
答案 0 :(得分:2)
来自MSDN WITH common_table_expression (Transact-SQL)
这是从一个简单的查询派生而来,并在执行中定义 单个 SELECT,INSERT,UPDATE或DELETE语句的范围。
CTE是表达式,将在执行第一个语句后处理,并且在
之后将不可用在您的情况下,您必须两次查询Scale
表以计算总和
DECLARE @Total DECIMAL(19,4) = (SELECT SUM(Net)/100.0 FROM Scales)
SELECT s.PlateID
, SUM(s.Net) AS Tonnage
, SUM(s.Net)/@Total AS Percentage
FROM Scales s
GROUP BY s.PlateID
答案 1 :(得分:1)
来自MSDN
公用表表达式(CTE)可以被认为是临时表 在单个执行范围内定义的结果集 SELECT,INSERT,UPDATE,DELETE或CREATE VIEW语句。 CTE是 类似于派生表,因为它不存储为对象和 仅持续查询的持续时间。
所以你可以尝试这样的事情,但你在查询中缺少Group by
WITH cte
AS (SELECT s.plate,
Sum(s.net) AS tonnage
FROM scale s
GROUP BY s.plate)
SELECT t.plate,
t.tonnage / ( Sum(tonnage) / 100.0 ) AS percentage,
Sum(tonnage) / 100.0 AS total
FROM cte t
Group by plate
答案 2 :(得分:1)
因为 CTE 的执行范围是针对单个SELECT,INSERT,UPDATE或DELETE语句。我想你应该为此而努力......
WITH cte AS (
SELECT s.plate, SUM(s.net) AS tonnage
FROM scale s
GROUP BY s.plate
)
SELECT t.*,
t.tonnage / ( Sum(tonnage) / 100.0 ) AS percentage
FROM cte t;