以下是我的示例表:
为了论证,请注意,任何餐厅(即使将来)都不会超过3件商品。
答案 0 :(得分:0)
如果销售的商品不超过3件,则固定查询可能为:
SELECT
tr.name restaurant
, tr.is_open open
, max(case when rn=1 then item_sold end) item_sold_1
, max(case when rn=2 then item_sold end) item_sold_2
, max(case when rn=3 then item_sold end) item_sold_3
FROM restaurants tr LEFT JOIN
( select restaurant_id, item_sold
,row_number() over (partition by restaurant_id order by 1) rn from items_sold
) ti
ON (tr.restaurant_id=ti.restaurant_id)
GROUP by tr.name, tr.is_open, 3;
表格结构:
create table restaurants
(
restaurant_id integer primary key not null,
name varchar(255),
is_open varchar(3)
);
create table items_sold
(
item_entry_id integer primary key not null,
item_sold varchar(255),
restaurant_id integer references restaurants
);
如果需要3个以上的项目,则必须根据items_sold对象中的唯一值计数动态生成SQL。