试图获得一个SQL命令,从每个月获得新客户,但我似乎无法让它工作

时间:2018-05-15 09:31:23

标签: sql sql-server labview

我试图从SQL数据库中提取每个月的新客户。我试过这个:

SELECT COUNT (Name) 
FROM Customer 
WHERE Date_created BETWEEN CONVERT(date, getdate()) AND CONVERT(date, getdate()) - (30)

4 个答案:

答案 0 :(得分:0)

您可以使用convert(varchar(6), getdate(), 112)yyyymm格式获取月份:

SELECT  convert(varchar(6), getdate(), 112) as Month
,       count(*)
FROM    Customer
GROUP BY
        convert(varchar(6), getdate(), 112)

答案 1 :(得分:0)

标准SQL:

select
   extract(year from Date_created) as yr
  ,extract(month from Date_created) as mth
  ,count(*) 
from Customer
group by
   extract(year from Date_created) as yr
  ,extract(month from Date_created) as mth
order by yr, mth

EXTRACT替换为DBMS中的匹配函数,例如对于SQL Server datepart(year, date)

答案 2 :(得分:0)

从您的查询中我认为这样做会更简单:

SELECT COUNT (Name) FROM Customer WHERE MONTH(Date_created)= MONTH(GETDATE())

虽然我不确定这是你所期望的,因为你的问题可以通过多种方式解释

编辑:考虑到不同年份:

SELECT COUNT (Name) FROM Customer 
WHERE MONTH(Date_created)= MONTH(GETDATE())
AND YEAR(Date_created)= YEAR(GETDATE())

答案 3 :(得分:0)

我不喜欢将BETWEEN与日期结合使用(请参阅此博客What do BETWEEN and the Devil Have in Common)。但是,查询的问题是日期顺序错误。较小的值必须先行:

SELECT COUNT(Name) 
FROM Customer 
WHERE Date_created BETWEEN CONVERT(date, getdate() - 30) AND CONVERT(date, getdate())

这写得更好:

SELECT COUNT(Name)
FROM Customer
WHERE Date_Created >= CONVERT(date, getdate() - 30) AND
      Date_Created < CONVERT(date, getdate());

我不确定这是否符合您对&#34; month&#34;的定义,但至少查询将返回30天的创建时间。