根据其他CTE的结果进行CTE

时间:2013-06-14 21:26:42

标签: sql sql-server tsql

我有几个加入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吗?任何帮助将不胜感激。

2 个答案:

答案 0 :(得分: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 )

答案 1 :(得分:1)

这是我曾经使用过几次的格式,其中临时表用于缓冲一个输出的复杂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中也很方便。