简体   繁体   English

具有不同聚合的SQL查询计数

[英]SQL Query with different aggregation for count

Publisher 出版者

pub_id  title_id    city

1         1           NY
1         2           NY
2         3           CA
3         4           VA

Titles 标题

title_id    price   genre
1            10     Horror
2             5     Bio
3            50     Science

Question: 题:
Create a SQL query that gives 创建一个SQL查询
-pub_id -pub_id
-# titles -#标题
-# titles with Horror genre -#种带有恐怖体裁的标题

I have been having hard time writing this SQL query and can't figure out how to include both #titles and #titles with horror genre in the same query. 我一直很难编写此SQL查询,并且无法弄清楚如何在同一查询中同时包含#titles和#titles及其恐怖类型。 I would appreciate any help on this. 我将不胜感激。 Thank you. 谢谢。

Query I have tried so far( don't know how to incude titles with horror genre): 到目前为止我已经尝试过的查询(不知道如何使用恐怖体裁来显示标题):

select a.pub_id, count(a.titles) 
from publisher a 
  left join titles b on a.title_id = b.title_id group by a.pub_id

If I use having then I won't be able to calculate the total number of titles. 如果我使用的话having那么我将无法计算标题的总数。

use following query to achieve your results 使用以下查询来实现您的结果

select 
   pub_id,
   count(*) as [titles], 
   SUM(CASE WHEN genre='horror' then 1 else 0 END) as [horror titles] 
from Publisher a
inner join titles b on a.title_id=b.title_id
group by
pub_id

you can use CASE statements to do this 您可以使用CASE语句执行此操作

you can use this query to get expected output 您可以使用此查询来获得预期的输出

select t.pub_id, COUNT(t.title_id) as title_id, t2.genre
from table1 t
 inner join 
 table2 t2 
on t.title_id = t2.title_id and t2.genre like 'Horror%'
group by t.pub_id, t2.genre

Note: change table1 and table2 names into your table name 注意:将table1和table2名称更改为您的表名称

the output is shown here 输出显示在这里

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM