我有一些复杂的连接语句,想要让它变得更容易。(或者保持它,但要正常工作:))
CREATE TABLE #Temp1
(
ID INT IDENTITY,
Name1 VARCHAR(100),
Value1 INT
)
CREATE TABLE #Temp2
(
ID INT IDENTITY,
Name2 VARCHAR(100),
Value2 INT,
Value1 INT
)
INSERT INTO #Temp1
SELECT 'Nm_1', 111 UNION ALL
SELECT 'Nm_2', 222
INSERT INTO #Temp2(Name2, Value2)
SELECT 'Nm_3', 333 UNION ALL
SELECT 'Nm_4', 444 UNION ALL
SELECT 'Nm_5', 555 UNION ALL
SELECT 'Nm_6', 666 UNION ALL
SELECT 'Nm_7', 777 UNION ALL
SELECT 'Nm_8', 888 UNION ALL
SELECT 'Nm_9', 999 UNION ALL
SELECT 'Nm_4', 444 UNION ALL
SELECT 'Nm_5', 555 UNION ALL
SELECT 'Nm_6', 666 UNION ALL
SELECT 'Nm_7', 777 UNION ALL
SELECT 'Nm_8', 888 UNION ALL
SELECT 'Nm_9', 999 UNION ALL
SELECT 'Nm_10',100 UNION ALL
SELECT 'Nm_11',110
这是两张桌子。 普通的第一个表,可以有任意数量的行。第二个取决于第一个。我解释如何。 #Temp2表中的第一行是静态的,从2到7的行重复与#Temp1中的计数一样多,最后3行也是静态的。
在我的考试中,我在#Temp1中有两行,所以
SELECT 'Nm_4', 444 UNION ALL
SELECT 'Nm_5', 555 UNION ALL
SELECT 'Nm_6', 666 UNION ALL
SELECT 'Nm_7', 777 UNION ALL
SELECT 'Nm_8', 888 UNION ALL
SELECT 'Nm_9', 999 UNION ALL
是两次,如果我有3则会有6 * 3行。
现在我想以这种方式在#Temp2表中更新Value1列。
从#Temp1中选择Value1,其中ID = 1
此值将写入#Temp2表,其中ID&gt; = 2且ID <= 7
从#Temp1中选择Value1,其中ID = 2
应位于#Temp2表中,其中ID&gt; = 8且ID <= 13。
我尝试写这样的连接
UPDATE #Temp2
SET Value1 = a.Value1
FROM #Temp1 AS a
INNER JOIN #Temp2 AS b
ON 2*a.ID - b.ID IN (-(2*a.ID-1)-(a.ID-2),
-(2*a.ID-1)-(a.ID-1),
-(2*a.ID-1)-(a.ID-0),
-(2*a.ID-1)-(a.ID+1),
-(2*a.ID-1)-(a.ID+2),
-(2*a.ID-1)-(a.ID+3))
但这是错误的,如果你运行这个脚本,你可以看到。 有人可以帮忙吗?
显然应该使用ID列
进行加入答案 0 :(得分:2)
这个简单的加入工作:
UPDATE #Temp2
SET Value1 = a.Value1
FROM #Temp1 AS a
INNER JOIN #Temp2 AS b
ON b.ID BETWEEN (a.ID*6-4) AND (a.ID*6+1)
答案 1 :(得分:0)
您可以将子查询与CASE WHEN
一起使用。
您可以使用BETWEEN
标记来处理您的ID。
UPDATE #Temp2
SET #Temp2.Value1 = (CASE WHEN ID BETWEEN 2 AND 7 THEN (SELECT a.Value1 FROM #Temp1 a WHERE a.ID = 1)
WHEN ID BETWEEN 8 AND 13 THEN (SELECT a.Value1 FROM #Temp1 a WHERE a.ID = 2)
END)
WHERE #Temp2.ID BETWEEN 2 AND 13
答案 2 :(得分:0)
你可以试试这个可以解决你的问题:
DECLARE @Counter int = 0,
@Rows int
Set @Rows = (Select count(*) from #Temp1)
While (@Counter < @Rows)
Begin
Update #Temp2
Set Value1 = (Select Value1 from #Temp1 where ID = @Counter + 1)
Where ID between 2 + (@Counter * 6) and 7 + (@Counter * 6)
Set @Counter = @Counter + 1
End