我有一个名为@myTable的表,该表返回一个称为am_id的循环增量值。我将一些ID为ID的变量存储在另一个名为@myTableVariable的表中。
DECLARE @myTable TABLE (id INT, name varchar(20))
insert into @myTable values(1,'one '),(2,'two '),(3,'three'),(4,'four'),(5,'five'),(6,'six'),(7,'seven'),(8,'eight'),(9,'nine'),(10,'ten'),(11,'eleven'),(12,'twelve'),(13,'thirteen')
DECLARE @myTableVariable TABLE (id INT, name varchar(20))
insert into @myTableVariable values(1,'Roberto'),(2,'Gail'),(3,'Dylan'),(4,'Ben')
select * from @myTableVariable
declare @start decimal(10)=1;
declare @end decimal(10)=4;
declare @increment decimal(10)=1;
SELECT f.name, (@start + @increment * (row_number() over (order by id) - 1) % cast(1 + round((@end - @start) / @increment, 0) as int)) AS am_id
FROM @myTable AS f
我想在@ myTable.am_id = @ myTableVariable.id上联接两个表,但是无法使用别名联接...
SELECT f.name, (@start + @increment * (row_number() over (order by id) - 1) % cast(1 + round((@end - @start) / @increment, 0) as int)) AS am_id
FROM @myTable AS f
LEFT JOIN @myTableVariable AS v ON v.vid = am_id
有什么想法可以加入这些表格吗?
非常感谢
答案 0 :(得分:1)
使用子查询,然后加入
SELECT * FROM (
SELECT name, (@start + @increment * (row_number() over (order by id) - 1) % cast(1 + round((@end - @start) / @increment, 0) as int)) AS am_id
FROM @myTable) AS f
LEFT JOIN @myTableVariable AS v ON v.id = f.am_id