显示购买组合餐的项目的SQL语句比购买单个项目便宜

时间:2015-09-21 23:37:57

标签: sql oracle

*注意!我要求学习原因我不知道如何编写这个查询,我在参考文献中找不到类似的东西。

Hello堆栈,所以我将此查询作为在子查询中使用临时表进行连接的示例,我完全不知道如何执行此操作。出于学习原因,我主要是这样做的。以下是示例中使用的两个表。同样,查询是:显示购买组合比购买单个商品更便宜的商品。

create table items(
I# varchar2 (20),
IName varchar2(20),
UnitPrice Number)
;

insert into items
values ('101','Cheese Burger',3.99);
insert into items
values ('102','Double Cheeseburger',4.99);
insert into items
values ('103','French Fries',1.19);
insert into items
values ('104','Medium Drink',1.39);
insert into items
values ('105','Large Drink',1.89);
insert into items
values('106','Combo 1',6.99);
insert into items 
values('107','Combo 2',8.99);

create table itemdetails(
I# varchar2(20),
IncludeI# varchar2(20)
);

insert into itemdetails
values ('106','101');
insert into itemdetails
values ('106','103');
insert into itemdetails
values ('106','104');
insert into itemdetails
values ('107','102');
insert into itemdetails
values ('107','103');
insert into itemdetails
values ('107','105');

任何答案都将不胜感激。我正在使用标准的oracle SQL。

2 个答案:

答案 0 :(得分:1)

您可以查询组合的总和(这是临时表),例如。

select sum(I1.UnitPrice)
from items as I1, itemdetails as I2
where I1.I# = I2.I#
and I1.i# = [one I'm looking at]
group by I1.I#

然后搜索组合价格

select I3.IName
from items I3
where UnitPrice < [individual prices of I3.I#]

然后结合两者。

select I3.IName
from items I3
where UnitPrice < 
(
    select sum(I1.UnitPrice)
    from items as I1, itemdetails as I2
    where I1.I# = I2.I#
    and I1.I# = I3.I#
    group by I1.I#
)

答案 1 :(得分:0)

您可以itemdetails加入items两次,一次是针对组合的价格,一次是针对单个项目的价格:

SELECT   combo.name, combo.UnitPrice
FROM     itemdetails id
JOIN     items combo ON id.i# = combo.i#
JOIN     items individual ON id.i# = individual.IncludeI#
GROUP BY combo.name, combo.UnitPrice
HAVING   combo.UnitPrice < SUM(individual.UnitPrice)