每月计算记录

时间:2015-04-28 07:37:25

标签: sql sql-server sql-server-2008 count

我正在尝试计算2014年每个月的约会数量,其中日期格式为'22 -JAN-14' 到目前为止,我已经尝试了这两个代码的变体,并且都提出了“YEAR”:无效的标识符。

代码1

SELECT count(*), MONTH(dateofappointment) as month, YEAR(dateofappointment) as year
FROM appointment
GROUP BY month
HAVING YEAR(dateofappointment) ='14'
ORDER BY month;

和CODE 2

select count(*)
from appointment
group by month(dateofappointment)
having year(dateofappointment) = '14';

感谢任何帮助。

3 个答案:

答案 0 :(得分:4)

使用Extract参考

SELECT EXTRACT(month FROM dateofappointment) "Month", count(*)
FROM appointment
WHERE EXTRACT(YEAR FROM dateofappointment) = '2014'
GROUP BY EXTRACT(month FROM dateofappointment)
ORDER BY EXTRACT(month FROM dateofappointment);

要有月份名称而不是数字

SELECT TO_CHAR(TO_DATE(EXTRACT(month FROM dateofappointment), 'MM'), 'MONTH') "Month", count(*)
FROM appointment
WHERE EXTRACT(YEAR FROM dateofappointment) = '2014'
GROUP BY EXTRACT(month FROM dateofappointment)
ORDER BY EXTRACT(month FROM dateofappointment);

答案 1 :(得分:0)

你的年份应该是一个整数 此外,除非您的约会发生在第一世纪,否则您的年份应该是2014年。

试试这个:

select  EXTRACT(month FROM dateofappointment), count(*)
from appointment
where EXTRACT(year FROM dateofappointment) = 2014
group by EXTRACT(month FROM dateofappointment)

答案 2 :(得分:0)

按月和年的数据,按日期从最旧到最新排序:

SELECT
    EXTRACT(year FROM dateofappointment) "Year",
    EXTRACT(month FROM dateofappointment) "Month",
    count(*) 
FROM
    appointment 
GROUP BY
    EXTRACT(year FROM dateofappointment),
    EXTRACT(month FROM dateofappointment) 
ORDER BY
    1,
    2;