简体   繁体   English

SQL Server:获取当前月份和前几个月

[英]SQL Server: get current month and previous months

I have a table with a column dateE that is formatted as nvarchar(20) and contains dates in the format yyyy-mm-dd. 我有一张表,其列dateE的格式为nvarchar(20)并包含格式为yyyy-mm-dd的日期。 The below stored procedure fetches all records from this table with dateE from Apr 2014: 以下存储过程从2014年4月开始使用dateE从该表中获取所有记录:

BEGIN
    SET NOCOUNT ON;
    SELECT      cat,
                COUNT(*) AS groupCount
    FROM        Log_PE 
    WHERE       dateE LIKE '2014-04%'
    GROUP BY    cat
    ORDER BY    groupCount desc, cat
END

How can I change this so that I don't have to hard-code the date and instead it always uses the current year and month for this ? 我该如何更改它,这样我就不必对日期进行硬编码,而是始终为此使用当前的年和月?

In addition, I would like to use the same stored procedure to also fetch the same data from the previous three months (in this case Jan, Feb, March 2014) so that in the end I have a ranking like in my example but for each of the above months. 此外,我想使用相同的存储过程从前三个月(在本例中为2014年1月,2月,2014年3月)中获取相同的数据,以便最终获得与示例相同的排名,但每个在上述月份中。

Can anyone here help me with this ? 这里有人可以帮助我吗?

Many thanks in advance, Tim. 蒂姆,非常感谢。

Instead of comparing strings, compare dates. 而不是比较字符串,而是比较日期。 Try this: 尝试这个:

SELECT      cat, COUNT(*) AS groupCount
FROM        Log_PE 
WHERE       CONVERT(DATE, dateE, 120) >= 
              CONVERT(DATE, CONVERT(VARCHAR(6), GETDATE(), 112) + '01', 112)

GROUP BY    cat
ORDER BY    groupCount desc, cat

Explanation: 说明:

--Convert your string date column to a date type (yyyy-mm-dd --> 120)
CONVERT(DATE, dateE, 120)

--Convert the current date to yyyymmdd format (style 112) 
--and get the first 6 characters. ie; Year and month
CONVERT(VARCHAR(6), GETDATE(), 112) 

--Add `'01'` to the `yyyymm` and convert back to a date type
CONVERT(DATE, CONVERT(VARCHAR(6), GETDATE(), 112) + '01', 112) 

尝试使用此日期表达式:

...where dateE LIKE convert(varchar (7), GETDATE(), 20) + '%'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM