计数查询 Reciepe/Ingredients

Count Query Reciepe/Ingredients

基本上我一直在研究一个 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;

试试这个:

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;

我不明白。您显示了来自 table RespIngr 的查询,但您没有提到这样的 table。您显示 table RecpIngr 但不包含字段 ingrDesc.

要获取您显示的字段,查询必须包含包含食谱和成分的 table 与包含成分描述的 table 的连接。

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;