英文:
How to select specific rows twice?
问题
使用UNION ALL
可以实现这个目标。是否还有其他方法?
英文:
I want to query some rows and in the resultset I want a subset of these rows twice.
With UNION ALL
I can achieve this.
Are there other ways?
答案1
得分: 3
以下是翻译好的部分:
你可以使用连接来复制行,例如根据条件。
对于具有值('one', 1), ('two', 2), ('three', 3), ('four', 4)的 stackoverflow (foo, bar)
,假设您希望始终有一份行的副本,对于偶数bar值的记录进行复制,并且对于以't'开头的foo记录进行复制。您可以有条件地连接明确的值子句:
select so.*
from stackoverflow so
inner
join (values (1), (2), (3)) copies(no)
on copies.no = 1 -- 始终有一份副本
or (copies.no = 2 and so.bar % 2 = 0) -- 偶数bar记录的副本
or (copies.no = 3 and so.foo like 't%') -- 以't'开头的foo记录的副本
您将获得以下结果:1的一行,2的三行(因为它是偶数且以't'开头),3的两行(因为以't'开头),4的两行(因为是偶数)。
英文:
You can use a join to multiplicate rows, for example on a condition.
With stackoverflow (foo, bar)
with values ('one', 1), ('two', 2), ('three', 3), ('four', 4) imagine you want to have one copy of rows always, duplicate records with even bar value and maybe duplicate records for foo starting with 't'. You can join an explicit values clause conditionally:
select so.*
from stackoverflow so
inner
join (values (1), (2), (3)) copies(no)
on copies.no = 1 -- first copy always
or (copies.no = 2 and so.bar % 2 = 0) -- a copy for even bar records
or (copies.no = 3 and so.foo like 't%') -- a copy for foo starting with 't'
you'll get one row for 1, three rows for 2 (because it's even and starts with t), two rows for 3 (because starts with t) and two rows for 4 (because even).
答案2
得分: 0
create table my_table(id int, name varchar(10));
insert into my_table values (1, 'Kenny'), (2, 'Eric'), (3, 'Stan'), (4, 'Kyle');
Eric is bigger, he needs three rows, so let's make them recursive way:
with rec(id, name, copy) as (
select id, name, 1 from my_table union all
select id, name, copy + 1 from rec where name = 'Eric' and copy < 3)
select id, name, copy from rec
英文:
Let's say we have this table:
create table my_table(id int, name varchar(10));
insert into my_table values (1, 'Kenny'), (2, 'Eric'), (3, 'Stan'), (4, 'Kyle');
Eric is bigger, he needs three rows, so let's make them recursive way:
with rec(id, name, copy) as (
select id, name, 1 from my_table union all
select id, name, copy + 1 from rec where name = 'Eric' and copy < 3)
select id, name, copy from rec
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论