简体   繁体   中英

Join Existing table with Temp Table

I pass year value to input parameter(@Year) of my proc

    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

I want to get result set for next 4 years. So I created temp table as below.

    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)

But How can I join temp table with other query.

Try the below query. Uses a simple JOIN on @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

You can just use a CROSS JOIN or an INNER JOIN with condition 1 = 1. You really probably don't need a temp table either. It does appear you're using SQL Server so I'm kind of assuming that even though the query is readily adaptable to other platforms.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM