选择特定行两次?

huangapple go评论67阅读模式
英文:

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的两行(因为是偶数)。

dbfiddle.uk 实时演示

英文:

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).

dbfiddle.uk live demo

答案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

dbfiddle demo

英文:

Let's say we have this table:

create table my_table(id int, name varchar(10));
insert into my_table values (1, &#39;Kenny&#39;), (2, &#39;Eric&#39;), (3, &#39;Stan&#39;), (4, &#39;Kyle&#39;);

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 = &#39;Eric&#39; and copy &lt; 3)
select id, name, copy from rec 

dbfiddle demo

huangapple
  • 本文由 发表于 2023年5月11日 11:47:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/76224023.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定