SQL Server如何获取每个类别下的新闻数量

时间:2016-07-27 11:09:53

标签: sql sql-server

计数总是1,但我需要得到的是每个类别下的新闻数量或数量。喜欢类别体育有2个新闻和类别技术有4个新闻:

select  
    News.NewsId, News.NewsTitle, 
    COUNT(News.NewsId) as Total 
from 
    News  
group by  
    News.NewsId, News.NewsTitle
inner join 
    NewsCategory on News.NewsId = NewsCategory.NewsId 
where 
    NewsCategory.CategoryId in (Select CategoryId 
                                from Category 
                                where CategoryName = 'travel' 
                                  or  CategoryName = 'Technology' 
                                  or CategoryName = 'Sport')
group by 
    n.NewsId, n.NewsTitle

3 个答案:

答案 0 :(得分:2)

我认为应该这样做:

select
  C.CategoryName,
  count(N.NewsId) as Total 
from News N 
  inner join NewsCategory NC 
    on N.NewsId = NC.NewsId
  inner join Category C
    on NC.CategoryId = C.CategoryId
where 
  upper(C.CategoryName) in ('TRAVEL', 'TECHNOLOGY', 'SPORT')
group by 
  C.CategoryName

答案 1 :(得分:1)

NewsCategory.CategoryI分组,或者如果您需要所有新闻信息OVER - 子句:

select  News.NewsId,
        News.NewsTitle,
        CategoryName, 
        CountInGroup = COUNT(*) OVER (PARTITION BY NewsCategory.CategoryId)
from News  
inner join NewsCategory
    on News.NewsId = NewsCategory.NewsId 
where NewsCategory.CategoryId in (Select CategoryId 
                                  from Category 
                                  where  CategoryName = 'travel' 
                                     or  CategoryName = 'Technology' 
                                     or  CategoryName = 'Sport')

请注意,GROUP BY n.NewsId, n.NewsTitle是多余的,无论如何都会返回所有记录。这就是为什么你每次都得到数= 1。

答案 2 :(得分:0)

获取

的类别和编号
SELECT NewsCategory.CategoryId, Category.CategoryName, COUNT(News.NewsId) as Total 
FROM News  
INNER JOIN NewsCategory on News.NewsId = NewsCategory.NewsId 
INNER JOIN Category on Category.CategoryId = NewsCategory.CategoryId
                    AND UPPER(Category.CategoryName) IN ('TRAVEL','TECHNOLOGY','SPORT')
GROUP BY 
NewsCategory.CategoryId, Category.CategoryName