SQL 查询中有多个约束计数
SQL multiple constrained counts in query
我试图通过 1 个查询获得多个计数结果,其中每个结果都是前一个结果的子集。
所以我的 table 将被称为 Recipe
并具有这些列:
recipe_num(Primary_key) decimal,
recipe_added date,
is_featured bit,
liked decimal
我想要的是进行查询,该查询将 return 任何特定月份按天分组的点赞数量
- 食谱总数为 total_recipes、
- 被列为 featured_recipes、
的食谱总数
- 被推荐并获得超过 100 个赞的食谱总数 liked_recipes
正如您所看到的,它们都是计数的,每个都是前一个的子集。
理想情况下,我不想 运行 分开 select count's where that query the whole table 而是从前一个查询。
我不太擅长将计数与 Where、Having 等一起使用...并且不确定该怎么做,到目前为止,我通过在这里挖掘来管理以下内容。
select
recipe_added,
count(*) total_recipes,
count(case is_featured when 1 then 1 else null end) total_featured_recipes
from
RECIPES
group by
recipe_added
我不太确定为什么我必须在计数中使用 case 但我无法使用 WHERE 让它工作,我想知道这是否可行。
谢谢
在 COUNT()
中使用 CASE
表达式,您正在进行条件聚合,而这正是您满足此要求所需要的:
select recipe_added,
count(*) total_recipes,
count(case when is_featured = 1 then 1 end) total_featured_recipes,
count(case when is_featured = 1 and liked > 100 then 1 end) liked_recipes
from Recipes
group by recipe_added
不需要 ELSE null
因为 CASE
表达式的默认行为是 return null
当没有其他分支 return 值.
如果您想要特定月份的结果,比如 2020 年 10 月,您可以在 GROUP BY
:
之前添加一个 WHERE
子句
where format(recipe_added, 'yyyyMM') = '202010'
这将适用于 SQL 服务器。
如果您使用不同的数据库,那么您可以使用类似的方法。
我试图通过 1 个查询获得多个计数结果,其中每个结果都是前一个结果的子集。
所以我的 table 将被称为 Recipe
并具有这些列:
recipe_num(Primary_key) decimal,
recipe_added date,
is_featured bit,
liked decimal
我想要的是进行查询,该查询将 return 任何特定月份按天分组的点赞数量
- 食谱总数为 total_recipes、
- 被列为 featured_recipes、 的食谱总数
- 被推荐并获得超过 100 个赞的食谱总数 liked_recipes
正如您所看到的,它们都是计数的,每个都是前一个的子集。
理想情况下,我不想 运行 分开 select count's where that query the whole table 而是从前一个查询。
我不太擅长将计数与 Where、Having 等一起使用...并且不确定该怎么做,到目前为止,我通过在这里挖掘来管理以下内容。
select
recipe_added,
count(*) total_recipes,
count(case is_featured when 1 then 1 else null end) total_featured_recipes
from
RECIPES
group by
recipe_added
我不太确定为什么我必须在计数中使用 case 但我无法使用 WHERE 让它工作,我想知道这是否可行。
谢谢
在 COUNT()
中使用 CASE
表达式,您正在进行条件聚合,而这正是您满足此要求所需要的:
select recipe_added,
count(*) total_recipes,
count(case when is_featured = 1 then 1 end) total_featured_recipes,
count(case when is_featured = 1 and liked > 100 then 1 end) liked_recipes
from Recipes
group by recipe_added
不需要 ELSE null
因为 CASE
表达式的默认行为是 return null
当没有其他分支 return 值.
如果您想要特定月份的结果,比如 2020 年 10 月,您可以在 GROUP BY
:
WHERE
子句
where format(recipe_added, 'yyyyMM') = '202010'
这将适用于 SQL 服务器。
如果您使用不同的数据库,那么您可以使用类似的方法。