繁体   English   中英

如何仅匹配SQL Server中日期时间列中的月份和年份部分

[英]How to match only month and year part from datetime column in SQL Server

我有两个输入,月份和年份。

  selectedMonth = DDLMonth.SelectedItem.Value;//1
  SelectedYear = DDLYear.SelectedItem.Text.Trim();//2013

我想显示该特定月份和年份的预设记录,而不是仅显示日期。 我想证明注册员工

sql查询

select e.EnquiryId, RegistrationNumber, Name
from Branch as b
    left join Enq as e on b.Enqui = e.Enqu
where Reg = @RegNo
  and Pay=Cheque 

如果选择的月份= 1广告年份= 2015,我就需要。 如果存在于付款日期和支票中。 就像是:

where Registratio = @RegNo
  and Payment(month) = selectedMonth
  and payment(year) = selectedyear
  and chequere(month) = selected Month
  and chequere(year) = selected year

我的列支票和付款日期为datetime格式。

最有效的方法是在应用程序代码中构造一个日期:

selectedMonth = DDLMonth.SelectedItem.Value;//1
SelectedYear = DDLYear.SelectedItem.Text.Trim();//2013  

var date = new DateTime(int.Parse(SelectedYear), int.Parse(selectedMonth), 1);

然后将此日期作为参数传递给您的查询:

where RegistrationNumber = @RegNo
  and PaymentDate >= @Date
  and paymentdate < DATEADD(MONTH, 1, @Date)
  and chequereceiveddate >= @Date
  and chequerecieveddate < DATEADD(MONTH, 1, @Date);

这使您的查询可保存 ,并且意味着您不需要对列执行DATEPART()函数。

GarethD提供了最佳的解决方案,但是另一种实现方法是使用DATEPART。

例:

where RegistrationNumber = @RegNo
and DATEPART(month, PaymentDate) = selectedMonth
and DATEPART(year, PaymentDate) = selectedYear
and DATEPART(month, chequerecieveddate) = selectedMonth
and DATEPART(year, chequerecieveddate) = selectedYear

这只是一个DATEPART()的示例,如果您想查找某些月份的平均付款,该示例将更有用。

暂无
暂无

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

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