sql server选择属性但不按该属性分组

时间:2012-09-21 20:36:44

标签: group-by sql-server-2008-r2 aggregate-functions

我正在处理查询以计算给定月份和年份的结果数量。但是,我还需要使用完整日期来创建月份字符串。我知道select子句中的任何内容也必须在group by子句中。但是,我只想按月份和年份分组以获得正确的计数结果。我该如何解决这个问题?

SELECT category, Count(ID), MONTH(aDate) AS month , YEAR(aDate) AS year, aDate,
CONVERT(CHAR(4),aDate) , 100) + CONVERT(CHAR(4),aDate) , 120) as monthYear
FROM table
GROUP BY month, year, category

2 个答案:

答案 0 :(得分:1)

您不需要使用整个日期,只需使用convert语句作为您的小组的一部分

     SELECT category, 
        Count(ID), 
        MONTH(aDate) AS [month] , 
        YEAR(aDate) AS [year], 
        CONVERT(CHAR(4),aDate) , 100) + CONVERT(CHAR(4),aDate) , 120) as monthYear 
FROM table 
GROUP BY MONTH(aDate), 
        YEAR(aDate), 
        category,
        CONVERT(CHAR(4),aDate) , 100) + CONVERT(CHAR(4),aDate) , 120)

答案 1 :(得分:-1)

SELECT MAX(category), Count(ID), MONTH(aDate) AS month , YEAR(aDate) AS year, MAX(aDate),
CONVERT(CHAR(4),MAX(aDate)) , 100) + CONVERT(CHAR(4),MAX(aDate)) , 120) as monthYear
FROM table
GROUP BY MONTH(aDate), YEAR(aDate)