3

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

4 回答 4

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

如果您的数据包含超过一年的数据,如果您尚未确保仅在 where 子句中获取一年的数据,则应将年份包含在 group-and order by 子句(和 select 语句)中。

于 2015-07-06T14:21:14.283 回答
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)
于 2015-07-06T14:05:14.177 回答
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)
于 2015-07-06T14:05:39.403 回答
-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
于 2015-07-06T14:06:51.087 回答