SQl:按月和按年分组

时间:2010-07-17 02:49:05

标签: asp.net sql

您好我的代码不起作用,我试图按年份分组我的blogentries这里是我的sql

SELECT * FROM(
    SELECT WP_BlogEntries.BlogEntryID, WP_BlogEntries.AddedDate,
        WP_BlogEntries.AddedBy, WP_BlogEntries.BlogID, 
        WP_BlogEntries.Title, WP_BlogEntries.Description, WP_BlogEntries.Body,
        WP_BlogEntries.ReleaseDate, WP_BlogEntries.ExpireDate,
        WP_BlogEntries.Approved, WP_BlogEntries.Listed,
        WP_BlogEntries.CommentsEnabled, WP_BlogEntries.OnlyForMembers,
        WP_BlogEntries.ViewCount, WP_BlogEntries.Votes, 
        WP_BlogEntries.TotalRating
    FROM WP_BlogEntries
    WHERE WP_BlogEntries.ReleaseDate < GETDATE()
        AND WP_BlogEntries.ExpireDate > GETDATE()
        AND Approved = 1
        AND Listed = 1
        AND WP_BlogEntries.BlogID = @BlogID) MonthEntries 
    GROUP BY YEAR(ReleaseDate), MONTH(ReleaseDate)

2 个答案:

答案 0 :(得分:2)

了解错误消息会很有帮助。

如果您指定SELECT * FROM,则无法执行GROUP BY

唯一有效的列是GROUP BY中的列或聚合函数。

如果按年份和月份分组,则每行将包含一年和一个月,SQL无法知道要显示哪些其他列,因为可能有多个列。 (例如,一个月内有两个博客条目)

你的意思是ORDER BY吗?

答案 1 :(得分:0)

像这样: select convert(varchar(50),YEAR(date)) +'/'+convert (varchar(50), MONTH(date)) ,Name , COUNT( Name) ,[DATE] from table1 group by convert(varchar(50),YEAR(date)) +'/'+convert (varchar(50), MONTH(date)) ,Name,[date] order by [Date] Desc