按月排序Sql查询

时间:2015-07-06 14:02:51

标签: sql sql-server sql-date-functions

我的SQL查询为:

select dateName(month, DateAccessed) "Month"
, count(1) totalVisits
, count(distinct l.userName) UsersVisit
from and where clause goes here
group by dateName(monthDateAccessed)
order by Month

我得到的输出是

Month   totalVisits   UsersVisit
April         100       25
February      200       35
July          300       45
March         400       55
May           500       65

但我想要的输出是:

February      200       35
March         400       55
April         100       25
May           500       65
July          300       45

我怎么能得到这个?

4 个答案:

答案 0 :(得分:5)

使用month(DateAccessed)datepart(month, DateAccessed)提取月份编号,并在order by子句中使用该编号。但是,您还必须将其添加到group by子句中:

SELECT 
    DATENAME(month, DateAccessed) "Month", 
    COUNT(1) totalVisits, 
    COUNT(DISTINCT l.userName) UsersVisit 
FROM and where clause goes here
GROUP BY 
    MONTH(dateaccessed), 
    DATENAME(month, DateAccessed)
ORDER BY 
    MONTH(dateaccessed);

如果您的数据保存超过一年的数据,您应该在group-和order by子句(和select语句)中包含年份,如果您还没有确保只在where子句中获取一年的数据

答案 1 :(得分:0)

您只需将ORDER BY子句更改为按DateAccessed的月份编号排序:

select dateName(month, DateAccessed) "Month"
, count(1) totalVisits
, count(distinct l.userName) UsersVisit
from and where clause goes here
group by dateName(monthDateAccessed)
order by Month(DateAccessed)

答案 2 :(得分:0)

您是通过DATENAME订购的,这是一个字符串。尝试通过DATEPART(整数)进行排序:

select dateName(month, DateAccessed) "Month"
, count(1) totalVisits
, count(distinct l.userName) UsersVisit
from and where clause goes here
group by dateName(monthDateAccessed), DATEPART(mm, dateAccessed)
order by DATEPART(mm, dateAccessed)

答案 3 :(得分:-1)

添加一列month(DateAccessed) as MonthNo并按顺序设置此列。

select dateName(month, DateAccessed) "Month", month(DateAccessed) as MonthNo,
, count(1) totalVisits
, count(distinct l.userName) UsersVisit
from and where clause goes here
group by dateName(monthDateAccessed)
order by MonthNo