如何在sql server中使用group by获取类别计数?

时间:2017-07-24 06:09:30

标签: sql-server

您好我创建了一个查询获取类别计数,其中某段时间日期。在我的数据库中,我有3个表首先是category,subcategory,subcategoryfollow。现在我想要谁用户关注子类别然后我想计入类别。对于前用户A遵循类别1的3子类别,然后用户B遵循类别1的相同3子类别然后我想要计数的类别1在查询中得到2这样想要的结果但是没有得到这种类型的结果。

这是我的查询=>

select count(*) as Count,categroyName from categroy s inner join 
(
select SS.categroyId from subcategory ss 
inner join 
( 
    select count(*) as count,subcategoryId from subcategoryfollow SSS
    WHERE SSS.IsFollowed = 1  and CAST(SSS.InsertDateTime as date) >=  CAST('2017-07-21' as date)
    AND CAST(SSS.InsertDateTime as date) <= CAST('2017-07-22' as date)
    group by SSS.subcategoryId,SSS.UserId
   ) as tab on tab.subcategoryId = ss.subcategoryId group by SS.subcategoryId
  )  as res on res.categroyId = s.categroyId where s.IsDeleted = 0
GROUP BY res.categroyId,categroyName

这是我目前的o / p =&gt;

Count | categroyName
 1       playing 
 1       Reading 

这是我的预期o / p =&gt;

Count | categroyName
2       playing 
1       Reading 

表类别数据=&gt;

categroyId | Name 
 1           playing      
 2           Reading

表子类别数据=&gt;

subcategoryId | categroyId | Name
 1                1           cricket
 2                1           football
 3                1           wallyball 
 4                2           bibal
 5               2           story

表子类别关注数据=&gt;

Id | UserId | subcategoryId | IsFollowed | InsertDateTime
 1      10          1                1          2017-07-21 05:57:07.347
 2      10          2                1          2017-07-21 05:56:02.347
 3      10          3                1          2017-07-21 05:58:01.347
 4      11          1                1          2017-07-21 05:59:08.347
 5      11          2                1          2017-07-21 05:60:01.347
 6      11          3                1          2017-07-21 05:61:06.347
 7      13          4                1          2017-07-21 05:61:06.347
 8      13          5                1          2017-07-21 05:61:06.347

这是我的查询和结果。现在在我的桌子上玩类别商店3子类别像板球,足球,wallyball现在2个用户遵循这3个子类别所以我想要计数2为palying类别。所以请任何人知道怎么做。

2 个答案:

答案 0 :(得分:1)

我很难完全理解你的问题。你在寻找下面的查询。

SELECT c.Name, COUNT( DISTINCT UserId ) AS Cnt
FROM subcategory AS sc
    INNER JOIN subcategoryfollow AS scf ON sc.subcategoryId = scf.subcategoryId
    INNER JOIN categroy AS s ON sc.categroyId = s.categroyId
WHERE scf.IsFollowed = 1  and CAST(scf.InsertDateTime as date) >=  CAST('2017-07-21' as date)
    AND CAST(scf.InsertDateTime as date) <= CAST('2017-07-22' as date)
    AND s.IsDeleted = 0
GROUP BY sc.categroyId, c.Name

答案 1 :(得分:0)

根据您的示例数据和您的预期结果,尝试使用以下SQL语句:

SELECT ucount, category FROM (
SELECT COUNT(F.userid) AS ucount,C.name AS category 
FROM Category AS C 
INNER JOIN SubCategory AS S ON C.categoryid = S.categoryid
INNER JOIN SubCategoryFollow AS F ON S.subcategoryid = F.subcategoryid
GROUP BY S.name,C.name) AS UserCount
GROUP BY ucount,category;