将子查询结果应用于外部查询中的每一行

Apply subquery result to every row in outer query

我写了一个这样的子查询:

(
  SELECT SUM(X.kMax) 
        FROM (
            SELECT MAX(Val) AS kMax 
            FROM [Consumers] upc 
            GROUP BY upc.[Profile]
        ) X
)

它获取每个配置文件的最大值,然后将所有内容相加为 return 一个值。例如 99

如何将此值应用于外部查询中的每一行?

Table

ID   Maxed
1      99
2      99
3      99
4      99
5      99

您需要像下面这样编写您的查询。

select 
<columns>,
(
  SELECT SUM(X.kMax) 
        FROM (
            SELECT MAX(Val) AS kMax 
            FROM [Consumers] upc 
            WHERE UPC.ID=UT.ID
            GROUP BY upc.[Profile]
        ) X
)
from yourTable ut

您可以应用一个值使用CROSS APPLYOUTER APPLY

select 
  <columns>,
  X.kMax
from yourTable T
CROSS APPLY (
  SELECT SUM(X.kMax) AS kMax 
        FROM (
            SELECT MAX(Val) AS kMax 
            FROM [Consumers] upc 
            WHERE UPC.ID=UT.ID
            GROUP BY upc.[Profile]
        ) X
) X