根据年份和月份查找计数

时间:2014-04-15 01:57:47

标签: sql sql-server sql-server-2008 tsql

我想将这些值填充到临时表中以获得明年和月份的计数。此外,想要查找有多少用户访问该月份和该年份的表和行数。

非常感谢任何帮助。

 CREATE TABLE #form_counts
    (
      [Table name] SYSNAME ,      
      [Year] DATETIME NULL,
      [Month] DATETIME NULL,
      [Num_Of_Users] INT NULL,
      [Last updated] DATETIME NULL ,
      [Rows] INT NULL
    )

 declare @start_date datetime,@end_date datetime
 set @start_date='19990101'
 set @end_date='20140301'

   INSERT INTO #form_counts
   select * from form_counts

2 个答案:

答案 0 :(得分:0)

如果你想获得计数

Select Count(Year), Year 
From form_counts 
where year([Last updated]) between 1999 and 2014
    and month([Last updated])=1

如果要遍历上述查询中的记录,请在SQL

中使用游标

答案 1 :(得分:0)

试试这个,

请按照以下步骤操作,这将有助于您的需求:

第1步:表创建(form_counts):

       --User Table
       CREATE TABLE form_counts 
       ( 
         Projectid varchar(20),
         TaskId Varchar(20),
         Modifieddate smalldatetime,
         users varchar(20)
       )

       --Temp Table
       CREATE TABLE #Form_counts 
   (
     [Project Name]  VARCHAR(20),
     [No. of Rows Used] INT,
     [No. of Years Used] INT,
     [No. of Months Used] INT,
     [No. of  Users Used] INT
   )

第2步:将数据插入form_counts表

       INSERT INTO form_counts VALUES 
       ('CO123000','0000000','1900-01-01 00:00:00','SYSADMIN'),
   ('CO123000','AD00001','1998-01-10 00:00:00','Admin2'),
   ('CO123000','AD00003','1998-01-10 00:00:00','SYSADMIN'),
   ('CO123000','ADSERVADJR','2013-04-03 15:50:00','SYSADMIN'),
   ('CO123000','COSERVADJR','2013-04-09 17:09:00','SYSADMIN'),
   ('CO123000','DOSERVADJR','2013-05-08 14:28:00','SYSADMIN'),
   ('CO123000','PM00403','1998-02-15 00:00:00','Admin5'),
   ('CO123001','AD00003','1998-01-10 00:00:00','SYSADMIN'),
   ('CO123001','ADSERVADJR','2013-04-09 12:20:00','SYSADMIN'),
   ('CO123001','PM00403','1998-01-10 00:00:00','Admin5'),
   ('CO123001','TS00504','1998-01-10 00:00:00','SYSADMIN') 

第3步:Select * from form_counts

第4步:执行以下查询。

       Insert into #Form_counts
       SELECT  A.Project [Project Name],
    SUM(A.TRows) [No. of Rows Used],
    SUM(A.TotYearsUsed) [No. of Years Used],
    SUM(A.TotMonthsUsed) [No. of Months Used],
    MAX(DISTINCT A.ToTusers) [No. of Users Used]
       FROM 
    (
    SELECT Projectid [Project],
           COUNT(projectid) [TRows],
           COUNT(DISTINCT YEAR(Modifieddate)) [TotYearsUsed] ,
           COUNT(DISTINCT month(Modifieddate)) [TotMonthsUsed],
           COUNT(DISTINCT Users) [TotUsers]
    FROM form_counts 
    GROUP BY Projectid,YEAR(Modifieddate)
    ) A 
       GROUP BY A.Project
       ORDER BY A.Project DESC

Select * from #Form_counts

OutPut:

Project Name  No. of Rows Used  No. of Years Used  No. of Months Used   No. of Users Used
CO123000            7        3               5                     3
CO123001            4        2               2                 2

如有任何疑虑,请与我们联系。 谢谢, Srikanth S