如何在SQL中按列分组?

时间:2009-05-04 14:07:15

标签: sql sql-server sql-server-2005

我如何按时间分组?我尝试了这个,但它给出了错误“无效的列名'时间'。”:

select Count(Page) as VisitingCount, CONVERT(VARCHAR(5), Date, 108) as [Time]
from scr_SecuristLog   
where Date between '2009-05-04 00:00:00' and '2009-05-06 14:58'  
and [user] in (select USERNAME from scr_CustomerAuthorities)  
group by [Time] order by [VisitingCount] asc

5 个答案:

答案 0 :(得分:8)

尝试

GROUP BY CONVERT(VARCHAR(5),Date, 108)

始终确保按照select子句中没有聚合函数的所有内容进行分组。

答案 1 :(得分:6)

[时间]是列别名。尝试

SELECT 
      COUNT(Page) AS VisitingCount
    , CONVERT(VARCHAR(5),Date, 108) AS [Time] 
FROM
    scr_SecuristLog   
WHERE
    Date BETWEEN '2009-05-04 00:00:00' AND '2009-05-06 14:58'  
    AND
    [user] IN (
                SELECT 
                    USERNAME             
                FROM
                    scr_CustomerAuthorities 
                )  
GROUP BY
    CONVERT(VARCHAR(5),Date, 108) 
ORDER BY
    [VisitingCount] ASC 

答案 2 :(得分:1)

select Count(Page) as VisitingCount,CONVERT(VARCHAR(5),Date, 108) as [Time] from scr_SecuristLog   
where Date between '2009-05-04 00:00:00' and '2009-05-06 14:58'  
and [user] in(select USERNAME             
    from scr_CustomerAuthorities )  
group by CONVERT(VARCHAR(5),Date, 108) order by [VisitingCount] asc  

我修改了GROUP BY以包含[Time]的实际表达式,而不是列别名(因为这不能用于GROUP BY,只有ORDER BY })

答案 3 :(得分:0)

看起来Date就是这里的一个列,但它是一个关键字而没有引用。也许这就是问题(尽管没有经过测试):

select Count(Page) as VisitingCount,CONVERT(VARCHAR(5),[Date], 108) as [Time] from scr_SecuristLog   
where [Date] between '2009-05-04 00:00:00' and '2009-05-06 14:58'  
and [user] in(select USERNAME             
    from scr_CustomerAuthorities )  
group by [Time] order by [VisitingCount] asc 

答案 4 :(得分:0)

如果您不想重复日期转换(有时计算比简单转换更加强烈),那么您可以使用以下内容:

select * 
from ( select Count(page) .., ... As [Date] from ... where ...) UG
group by UG.[Date]

请注意,给内部选择提供'UG'名称,并且这种情况最有可能,并且在大多数情况下比在原始分组中重复转换表达式效率低。 你的整个表达也可能会改变......但是你知道这是可能的。