如何在sql server中使用某个类别使用group进行计数?

时间:2017-07-19 07:20:00

标签: sql-server

您好我正在创建一个查询,以确定谁用户按照我想要在每个时间段内计算的类别。 但是我的查询得不到正确的结果。我不知道查询中的问题在哪里。任何人都知道如何解决它。

这是我的查询=>

SELECT Name,count(SIF.InsertDateTime) as Count
 FROM dbo.InteresetInFollowers SIF
  INNER JOIN dbo.Users u on u.userid = sif.userid
  INNER JOIN dbo.SubCategoryIn ss on ss.SubCategoryInId = SIF.SubCategoryInId
  INNER JOIN dbo.CategoryIn s on s.CategoryInId = ss.CategoryInId
  WHERE SIF.IsFollowed = 1 
 GROUP BY Name,SIF.InsertDateTime

My current o/p =>
Name    |  Count
Cricket            5000
reading            1000

My expacted o/p =>
Name    |  Count
Cricket            2
reading            3

Here In my data base like this data is store =>

CategoryIn =>
 CategoryInId | Name
 1              Cricket
 2              reading



 SubCategoryIn =>
 SubCategoryInId |   CategoryInId      | Name
  1                    1                  balling
  2                    1                  batsman
  3                    2                  baybal
  4                    2                  story

 InteresetInFollowers=>
  InteresetInId | UserId | SubCategoryInId | IsFollow | InsertDateTime
  1                10        1                 1        2017-07-19 14:23:30.703
  2                20        2                 1       2017-07-19 14:23:30.703
  3                30        3                 1       2017-07-19 14:23:30.703 
  4                40        4                 1       2017-07-19 14:23:30.703
  5                50        3                 1       2017-07-19 14:23:30.703

1 个答案:

答案 0 :(得分:1)

固定。

SELECT name
,count(*) AS Count
FROM dbo.InteresetInFollowers SIF
INNER JOIN dbo.Users u ON u.userid = sif.userid
INNER JOIN dbo.SubCategoryIn ss ON ss.SubCategoryInId = SIF.SubCategoryInId
INNER JOIN dbo.CategoryIn s ON s.CategoryInId = ss.CategoryInId
WHERE SIF.IsFollowed = 1 AND CAST(InsertDateTime AS DATE) = CAST(GETDATE() AS DATE)
GROUP BY name