0

我有几个加入 CTE。就像是:

;With CT1 AS(SELECT ..)
, CT2 AS(select)
SELECT *.T1,*T2 FROM CT1 T1 INNER JOIN CT2 T2 WHERE (some Condition ) GROUP BY (F1,F2, etc)

现在我需要将此查询的结果连接到另一个 CTE。最好的方法是什么?我可以用这个查询的结果做一个 CTE 吗?任何帮助将不胜感激。

4

2 回答 2

2

您可以根据之前定义的 CTE 继续创建新的 CTE。它们可以加入或以其他方式合并,但须遵守 CTE 的规则。

; with
  ArabicRomanConversions as (
    select *
      from ( values
        ( 0, '', '', '', '' ), ( 1, 'I', 'X', 'C', 'M' ), ( 2, 'II', 'XX', 'CC', 'MM' ), ( 3, 'III', 'XXX', 'CCC', 'MMM' ), ( 4, 'IV', 'XL', 'CD', '?' ),
        ( 5, 'V', 'L', 'D', '?' ), ( 6, 'VI', 'LX', 'DC', '?' ), ( 7, 'VII', 'LXX', 'DCC', '?' ), ( 8, 'VIII', 'LXXX', 'DCCC', '?' ), ( 9, 'IX', 'XC', 'CM', '?' )
        ) as Placeholder ( Arabic, Ones, Tens, Hundreds, Thousands )
      ),
  Numbers as (
    select 1 as Number
    union all
    select Number + 1
      from Numbers
      where Number < 3999 ),
  ArabicAndRoman as (
    select Number as Arabic,
      ( select Thousands from ArabicRomanConversions where Arabic = Number / 1000 ) +
      ( select Hundreds from ArabicRomanConversions where Arabic = Number / 100 % 10 ) +
      ( select Tens from ArabicRomanConversions where Arabic = Number / 10 % 10 ) +
      ( select Ones from ArabicRomanConversions where Arabic = Number % 10 ) as Roman
      from Numbers ),
  Squares as (
    select L.Arabic, L.Roman, R.Arabic as Square, R.Roman as RomanSquare
      from ArabicAndRoman as L inner join
        ArabicAndRoman as R on R.Arabic = L.Arabic * L.Arabic
      where L.Arabic < 16 ),
  Cubes as (
    select S.Arabic, S.Roman, S.Square, S.RomanSquare, A.Arabic as Cube, A.Roman as RomanCube
      from Squares as S inner join
        ArabicAndRoman as A on A.Arabic = S.Square * S.Arabic )
  select *
    from Cubes
    order by Arabic
    option ( MaxRecursion 3998 )
于 2013-06-15T00:45:05.667 回答
1

这是我使用过几次的格式,其中临时表用于缓冲一个复杂的 CTE,该 CTE 被输出,然后从 temp 中再次使用第二个 CTE。

如果您需要 2 个结果集,或者如果完整的 CTE 作为一个庞大的语句会导致速度问题(在某些情况下分解它可能会带来巨大的性能提升),那么它会很有用

-- I do this "DROP" because in some cases where query is executed over and 
-- over sometimes the object is not cleared before next transaction.
BEGIN TRY DROP TABLE #T_A END TRY BEGIN CATCH END CATCH;

WITH A AS (
    SELECT 'A' AS Name, 1 as Value
    UNION ALL SELECT 'B', 2
)
SELECT *
INTO #T_A
FROM A;

SELECT *
FROM #T_A ; -- Generate First Output Table

WITH B AS (
    SELECT 'A' AS Name, 234 as Other
    UNION ALL SELECT 'B', 456
)
-- Generate second result set from Temp table.
SELECT B.*, A. Value
FROM B  JOIN #T_A AS A ON A.Name=B.Name

这会产生一个 2 表结果集。这在 .NET 填充数据集时也很方便。

于 2013-06-15T01:34:40.310 回答