多部分标识符无法与WITH子句绑定

时间:2019-03-06 10:26:12

标签: sql-server

我已经计算了一张表的TOP 10运行总和,现在想以百分比的形式获取此pareto图,我有以下代码:

WITH
CTE as
(
    SELECT 
       [nWordNr] as W, 
       [nBitNr] as B,
       SUM([tmTotals]) as total,
       COUNT(*) as Amount
    FROM Messages_History
    GROUP BY nWordNr, nBitNr
),
totAlarms as
(
    select 
    count([nWordNr]) as cnt
    FROM Messages_History
)
SELECT TOP 10 *, 
    SUM(total) OVER (ORDER BY total desc) * 1.0 / totAlarms.cnt as Running
FROM   CTE
ORDER BY total desc

当我想使用totAlarms.cnt计算运行百分比时,出现以下错误:

The multi-part identifier "totAlarms.cnt" could not be bound.

如何使用totAlarms.cnt计算运行百分比。

4 个答案:

答案 0 :(得分:3)

WITH
CTE as
(
SELECT 
     [nWordNr] as W, 
     [nBitNr] as B,
     SUM([tmTotals]) as total,
     COUNT(*) as Amount
FROM Messages_History
GROUP BY nWordNr, nBitNr
),
  totAlarms as
  (
  select 
  count([nWordNr]) as cnt
  FROM Messages_History
  )
SELECT TOP 10 *, 
   SUM(total) OVER (ORDER BY total desc) * 1.0 / totAlarms.cnt as Running
FROM   CTE,totAlarms 
ORDER BY total desc

借助交叉联接,您可以实现它。 不能绑定多部分标识符“ totAlarms.cnt”。此错误表明您在联接或从中不使用totAlarms(CTE表)。

答案 1 :(得分:2)

CTE不会自动包含在附加查询中,您必须在FROMJOIN子句中提及它们。

您当前的查询格式为:

WITH
   CTE AS ( ... ),
   totAlarms  AS ( ... )
SELECT ...
FROM CTE
ORDER BY ...

因此,CTE子句中仅可见SELECTtotAlarms已定义但从未使用过-就像创建VIEW一样,但不编写任何引用它的查询。

由于您的两个CTE是独立的,因此您需要CROSS JOIN,并使用以下格式:

WITH
   CTE AS ( ... ),
   totAlarms  AS ( ... )
SELECT ...
FROM CTE
CROSS JOIN totAlarms
ORDER BY ...

或使用,运算符,该运算符实际上是交叉联接:

WITH
   CTE AS ( ... ),
   totAlarms  AS ( ... )
SELECT ...
FROM CTE, totAlarms
ORDER BY ...

答案 2 :(得分:1)

由于计数只是一个值,因此将其捕获在标量变量中:

DECLARE @totAlarms_cnt INT = (
                                  SELECT    COUNT([nWordNr]) as cnt
                                  FROM      Messages_History
                                  )
;
WITH
CTE as
(
SELECT 
     [nWordNr] as W, 
     [nBitNr] as B,
     SUM([tmTotals]) as total,
     COUNT(*) as Amount
FROM Messages_History
GROUP BY nWordNr, nBitNr
)

SELECT TOP 10 *, 
   SUM(total) OVER (ORDER BY total desc) * 1.0 / @totAlarms_cnt as Running
FROM   CTE
ORDER BY total desc

答案 3 :(得分:1)

与其编写sub CTE尝试创建变量和存储值并像下面那样使用

declare  @nWordNr int
select @nWordNr=count(nWordNr)  FROM Messages_History

;WITH
CTE as
(
SELECT 
[nWordNr] as W, 
[nBitNr] as B,
SUM([tmTotals]) as total,
COUNT(*) as Amount
FROM Messages_History
GROUP BY nWordNr, nBitNr
)--,
--totAlarms as
--(
--select 
--count([nWordNr]) as cnt
--FROM Messages_History
--)
SELECT TOP 10 *, 
SUM(total) OVER (ORDER BY total desc) * 1.0 / @nWordNr as Running
FROM   CTE
ORDER BY total desc