按月份对 Sql 查询进行排序

Sort Sql Query by Month

我有一个 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

我怎样才能得到这个?

您只需将 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)

您正在按 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)

添加一列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

使用 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);

如果您的数据保存了超过一年的数据,您应该在分组和排序子句(和 select 语句)中包含年份,如果您还没有确保只从where 子句中的一年。