简体   繁体   English

select 一个表中的内容使用另一个表

[英]select contents from one table using another table

I have two tables我有两张桌子

A1 A1 A2 A2
a一个 2 2
b b 3 3
A3 A3 A4 A4
a一个 row1第 1 行
a一个 row 2第 2 行
a一个 row 3第 3 行
a一个 row 4第 4 行
b b row 5第 5 行
b b row 6第 6 行
b b row 7第 7 行
b b row 8第 8 行
b b row 9第 9 行

I want something like我想要类似的东西

A3 A3 A4 A4
a一个 row1第 1 行
a一个 row 2第 2 行
b b row 5第 5 行
b b row 6第 6 行
b b row 7第 7 行

The second column in the first table should be the number of records i want from each group in the next table I tried where exists it did not work can you help me.??第一个表中的第二列应该是我想从下一个表中的每个组中获得的记录数我试过的地方存在它不起作用你能帮我吗??

I would use ROW_NUMBER here on the second table.我会在第二张桌子上使用ROW_NUMBER Then join to the first table and only retain records whose row number does not exceed the generated row number values.然后加入第一个表,只保留行号不超过生成的行号值的记录。

WITH cte AS (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY A3 ORDER BY A4) rn
    FROM Table2
)

SELECT t2.A3, t2.A4
FROM cte t2
INNER JOIN Table1 t1
    ON t2.A3 = t1.A1
WHERE
    t2.rn <= t1.A2;

下面演示链接的屏幕截图

Demo 演示

Note that it would be ideal to have a more proper sequence column in the second table which determines the order for choosing records there.请注意,最好在第二个表中有一个更合适的序列列,以确定在那里选择记录的顺序。

 declare @temp1 as table(A1 varchar(1),A2 varchar(1))
 declare @temp2 as table(A3 varchar(1),A4 varchar(10));

 insert into @temp1(A1,A2) values('a',2),('b',3)
 insert into @temp2(A3,A4) values('a','row 1'),
 ('a',  'row 2'),
 ('a',  'row 3'),
 ('a',  'row 4'),
 ('b',  'row 5'),
 ('b',  'row 6'),
 ('b',  'row 7'),
 ('b',  'row 8'),
 ('b',  'row 9')

 select A1,A4 
 from
 (
 select 
 tmp1.A1,tmp1.A2,tmp2.A4,
 Row_Number() over(partition by tmp1.A1 order by tmp1.A1) RowID
 from @temp1 tmp1
 join @temp2 tmp2 on
    tmp1.A1=tmp2.A3
 )x
 where RowID<=A2

output: output:

A1  A4
a   row 1
a   row 2
b   row 5
b   row 6
b   row 7

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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