A little missunderstood in GROUP BY ln SQL SERVER

for example i tried to view how much news posted grouping by week in year 2009


     SELECT 
        DATEPART(WK,DatePosted) AS WeekNumber, 
        COUNT(NewsID) AS NewsPosts
     FROM News
     WHERE DATEPART(YYYY, dbo.News.DatePosted) = 2009
     ORDER BY WeekNumber



you will get the warning message

error , Line 5
Column 'News.DatePosted' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.


what's wrong? yup you need to add the group by
so we are going to add the group by

    SELECT
        DATEPART(WK,DatePosted) AS WeekNumber,
        COUNT(NewsID) AS NewsPosts
    FROM News
    WHERE DATEPART(YYYY, dbo.News.DatePosted) = 2009
    GROUP BY WeekNumber
    ORDER BY WeekNumber

still error? try to use the column instead, it's because sql server group by only regonise the column in group by not alias (like in My SQL)


0 comments:

Posting Komentar