Count Query Reciepe / Ingredients

时间:2015-04-12 14:28:40

标签: sql oracle top-n

基本上我一直在研究一个SQL问题,这个问题要求显示每种成分以及它所包含的配方总数。它还必须包括出现超过10次的成分成分流行度和ingrdesc升序的降序。

表格如下:

CREATE TABLE Ingredient
(

idI NUMBER              constraint pk_Ingredient PRIMARY KEY ,

ingrDesc VARCHAR2(100)  constraint nn1Ingredient not null
);


CREATE TABLE Recipe
(

idR NUMBER                constraint pk_recipe PRIMARY KEY ,

recipeTitle VARCHAR2(200)  constraint nn1Recipe not null,
prepText VARCHAR2(4000),

cuisineType VARCHAR2(50),
mealType VARCHAR2(30) DEFAULT NULL,

CONSTRAINT ch_mealType CHECK (mealType IN ('starter', 'main', 'dessert', null))
);


CREATE TABLE RecpIngr
(

idR NUMBER ,

hidI NUMBER ,

CONSTRAINT pk_RecpIngr PRIMARY KEY (idR, idI),

CONSTRAINT fk1RecpIngr_recipe foreign key(idR) references Recipe,

CONSTRAINT fk2RecpIngr_ingredient foreign key(idI) references Ingredient
)
organization index;

到目前为止,我有这个问题:

SELECT ingrDesc,
COUNT (idR) As num_of_recipes
FROM RespIngr
WHERE num_of_recipes <10
ORDER BY num_of_recipes DES, ingrDes ASC;

2 个答案:

答案 0 :(得分:0)

试试这个:

SELECT ingrDesc,
COUNT (idR) As num_of_recipes
FROM RespIngr
GROUP BY ingrDesc
HAVING COUNT (idR) > 10
ORDER BY num_of_recipes DESC, ingrDesc ASC;

答案 1 :(得分:0)

我不明白。您显示表RespIngr中的查询,但未提及此类表。您显示的是表格RecpIngr,但不包含字段ingrDesc

要获取您显示的字段,查询必须包含包含配方和成分的表的连接以及包含成分描述的表。

with
RCount( IngID, RecipeCount )as(
    select  hidI, count(*)
    from    RecpIngr
    group by hidI
    having count(*) > 10
)
select  i.ingrDesc as "Ingredient", rc.RecipeCount as "Number of Recipes"
from    Ingredient  i
join    RCount      rc
    on  rc.IngID = i.idI;