admin

在T-SQL中,如何在子查询中引用表变量?

sql

我已经声明了一个表变量’@t’,并正确执行了’INSERT-INTO-
SELECT’。当我尝试对表变量进行一些额外的计算以获取每组行编号时,我收到错误,或者直接使用’@t’时出现“必须声明变量”,而使用’@t的别名时出现“无效的对象名”
‘。请指教。

SELECT 
    *,
    (SELECT COUNT(*) FROM "LTV" "COUNTER"
     WHERE 
        "COUNTER"."Collateral_ID" = "LTV"."Collateral_ID"
        AND
        "COUNTER"."m_il_no" = "LTV"."m_il_no"
        AND
        "COUNTER"."Ref_Key" <= "LTV"."Ref_Key"
     GROUP BY "COUNTER"."Collateral_ID", "COUNTER"."m_il_no"
    ) "MIL_IDX"

FROM @t AS LTV

阅读 150

收藏
2021-07-01

共1个答案

admin

使用:

SELECT x.*,
       y.num
  FROM @t x
  JOIN (SELECT t.collateral_id,
               t.m_il_no,
               COUNT(*) AS num
          FROM @t t
      GROUP BY t.collateral_id, t.m_il_no) y ON y.collateral_id = x.collateral_id
                                            AND y.m_il_no = x.m_il_no
2021-07-01