使用Temp Table加入现有表

时间:2015-08-04 05:18:58

标签: sql

我将年份值传递给我的proc的输入参数(@Year)

    SELECT @Year [Year]
    , t.Name AS [Town]
    , COUNT(r.Id) AS [PropertyCount]
    , CASE
        WHEN @Year - [Age] < 11 THEN '1-10'
        WHEN @Year - [Age] BETWEEN 11 AND 20 THEN '11-20'
        ELSE 'Unknown'
    END AS [AgeRange]
    FROM Properties  r 
    JOIN Towns t
        ON t.Id  = r.TownId
     WHERE t.Id = @TownId
    GROUP BY
      t.Name,
    CASE
        WHEN @Year - [Age] < 11 THEN '1-10'
        WHEN @Year - [Age] BETWEEN 11 AND 20 THEN '11-20'
        ELSE 'Unknown'
    END

我想获得未来4年的结果。所以我创建了如下的临时表。

    DECLARE @tempTable table(YearValue SMALLINT)
    INSERT INTO @tempTable VALUES (@Year )
    INSERT INTO @tempTable VALUES (@Year + 1)
    INSERT INTO @tempTable VALUES (@Year + 2)
    INSERT INTO @tempTable VALUES (@Year + 3)

但是如何将临时表与其他查询联系起来。

2 个答案:

答案 0 :(得分:0)

尝试以下查询。在JOIN

上使用简单的@temptable
SELECT tt.YearValue [Year]
    , t.Name AS [Town]
    , COUNT(r.Id) AS [PropertyCount]
    , CASE
        WHEN tt.YearValue - [Age] < 11 THEN '1-10'
        WHEN tt.YearValue - [Age] BETWEEN 11 AND 20 THEN '11-20'
        ELSE 'Unknown'
    END AS [AgeRange]

FROM 
@tempTable tt LEFT JOIN 
Properties  r 
     JOIN Towns t
        ON t.Id  = r.TownId
     WHERE t.Id = @TownId
    GROUP BY
      t.Name,
    CASE
        WHEN tt.YearValue - [Age] < 11 THEN '1-10'
        WHEN tt.YearValue - [Age] BETWEEN 11 AND 20 THEN '11-20'
        ELSE 'Unknown'
    END

答案 1 :(得分:0)

您可以使用条件1 = 1的CROSS JOIN或INNER JOIN。您可能也不需要临时表。它看起来你正在使用SQL Server,所以我有点假设即使查询很容易适应其他平台。

SELECT
    yr AS "Year", t.Name AS Town, COUNT(r.Id) AS PropertyCount,
    CASE
        WHEN yr - Age < 11 THEN '1-10'
        WHEN yr - Age BETWEEN 11 AND 20 THEN '11-20'
        ELSE 'Unknown'
    END AS AgeRange
FROM
    Properties as r INNER JOIN Towns as t ON t.Id  = r.TownId
    INNER JOIN (
        SELECT @Year as yr UNION ALL Select @Year + 1 UNION ALL
        SELECT @Year + 2   UNION ALL SELECT @Year + 3
    ) AS y ON 1 = 1 /* lots of variations on syntax here depending on your flavor of SQL */
WHERE t.Id = @TownId
GROUP BY
    yr,
    t.Name,
    CASE
        WHEN yr - Age < 11 THEN '1-10'
        WHEN yr - Age BETWEEN 11 AND 20 THEN '11-20'
        ELSE 'Unknown'
    END