SQL:从超集中检索缺失值

SQL: Retrieve missing values from superset

我有一个 table 这样的:

Device  | Rating
-----------------
iPhone  | 1
iPhone  | 2
iPhone  | 4
iPhone  | 5
Android | 3
Android | 5

我想 return table 获得所有可能的评分。在这种情况下 1 to 5。 所以我得到的 table 将是:

Device  | Rating
-----------------
iPhone  | 1
iPhone  | 2
iPhone  | 3
iPhone  | 4
iPhone  | 5
Android | 1
Android | 2
Android | 3
Android | 4
Android | 5

我试过使用类似的东西:

SELECT a.device, b.rating
FROM device_rating_table a
RIGHT JOIN rating_lookup_table b
ON a.rating = b.rating
GROUP BY 1,2
;

但这不起作用。您能为此提出解决方案吗?

您可以cross join数字介于 1 和 5 之间的不同设备的列表:

select d.device, r.rating
from (select distinct device from mytable) d
cross join generate_series(1, 5) as r(rating)

或者,如果您想根据 table 中的最小值和最大值生成评级范围:

select d.device, r.rating
from (select distinct device from mytable) d
cross join (select generate_series(min(rating), max(rating)) from mytable) as r(rating)

最后:如果 table 中的所有评分都可用,则无需使用 generate_series():

select d.device, r.rating
from (select distinct device from mytable) d
cross join (select distinct rating from mytable) r

您可以使用 with recursive:

with recursive cte as (
  select distinct device d, 1 r from devices
  union all
  select d, r + 1 from cte where r < 5
)
select * from cte order by d asc;