根据最近输入的月份和年份获取记录

时间:2017-08-22 14:21:23

标签: c# asp.net sql-server

我想从数据库中获取记录,具体取决于表中输入的最近月份和年份。表格中的列显示记录的月份和年份为月份和年份。下面是sp我有使用但它只以desc顺序获取记录。我只想从数据库中获取最近一个月和一年的所有记录。

ALTER PROCEDURE [dbo].[Proc_GetComplianceClientIDBy_ProfileID]
    @ProfileID varchar(100)
AS
BEGIN
    SET NOCOUNT ON;
    --Client Wise for the Currenct Month
select * into  #Client_Business_Mapping 
from TLConnectMasterDB.dbo.Client_Business_Mapping with(nolock) 
where CBM_CNM_ID=@profileID
select ClientID,CM_ClientName, SM.SM_Name as StateName, 
   LM.LM_Name as LocationName,CLM.CL_BranchName as BranchName,
   ROUND(convert(float,sum(CompliedNo)*100/convert(float, 
   (sum(CompliedNo)+sum(NotCompliedNo)))),2) Compliance,
   Round(convert(float,sum(NotCompliedNo)*100/convert(float,
  (sum(CompliedNo)+sum(NotCompliedNo)))),2) NotCompliance 
FROM RegulatoryDB..Monthly_Compliance_Summary MS WITH(NOLOCK)
   join #Client_Business_Mapping 
      on CBM_Client_ID=ClientID collate database_default
   join RegulatoryDB..Clients_Master CM with(nolock)  
      on CM_ClientID=CBM_Client_ID collate database_default
   join RegulatoryDB..Client_LocationMaster CLM with(nolock) 
      on CLM.CL_ClientID = CM.CM_ClientID 
          and MS.State = CLM.CL_StateID 
          and MS.Location = CLM.CL_CityID 
          and MS.Branch=CLM.CL_BranchName
   join RegulatoryDB..State_Master SM 
      on SM.SM_Code=CLM.CL_StateID
   join RegulatoryDb..Location_Master LM 
      on SM.SM_Code=LM.SM_Code and LM.LM_Code=CLM.CL_CityID
where CBM_CNM_ID=@ProfileID 
group by month, Year, ClientID, CM_ClientName, SM.SM_Name, 
   LM.LM_Name, CLM.CL_BranchName
Order by cast(Year as int) desc, cast(Month as int) desc
END

1 个答案:

答案 0 :(得分:0)

只需在where子句中添加其他谓词:

where CBM_CNM_ID=@ProfileID 
   and Month = Month(DateAdd(month, -1, getDate())) -- month for 1 month ago
   and Year = Year(DateAdd(month, -1, getDate()))  -- year for 1 month ago

但更好的方法是将一个计算列添加到包含日历月份的表中(为什么首先将这些部分存储在不同的列中?)

Alter table <table with month, year columns>
   Add SummaryDate As DATEFROMPARTS(year, month, 1)

然后您可以添加一个where子句谓词,该谓词在任何指定日期或之后返回所有摘要行:

where CBM_CNM_ID=@ProfileID 
   and SummaryDate >= @thresholDate