sql - Produce where clause for 5 months ago -


i'm haveing trouble case expression on line

datepart(yyyy, dateadd(mm, -5, getdate())) 

if delete line works fine if leave out selects records every decemeber , not december 2012 want.

i've searched everywhere , can't figure out.

select c.custid , sum(case datepart(mm, i.invoicedate) when datepart(mm, dateadd(mm, -5, getdate())) ,      datepart(yyyy, dateadd(mm, -5, getdate()))   ia.amount    else 0 end) 'total0' invoice  inner join invoiceamtsummary ia  on i.guidinvoice=ia.guidinvoice inner join customer c on  c.guidcustomer=i.guidcustomer group c.custid 

i think want

select             c.custid,             sum             (                 case                      when       datepart(mm, i.invoicedate) = datepart(mm, dateadd(mm, -5, getdate()))   ,       datepart(yyyy, i.invoicedate) = datepart(yyyy, dateadd(mm, -5, getdate()))                         ia.amount                     else                         0                 end             ) [total0]                  invoice          join             invoiceamtsummary ia                   on i.guidinvoice = ia.guidinvoice         join             customer c                  on  c.guidcustomer = i.guidcustomer     group             c.custid 

or, more sensibly

declare @targetdate datetime; declare @targetyear int; declare @targetmonth month;  set @tagetdate = dateadd(mm, -5, getdate())); set @targetyear = year(@targetdate); set @targetmonth = month(@targetdate);  select             c.custid,             sum(coalesce(ia.amount, 0))                  customer c          left join             (              select                          month(i.invoicedate) month,                          year(i.invoiceyear) year,                          i.guidinvoice,                          i.guidcustomer                                          invoice             ) s                 on s.guidcustomer = c.guidcustomer          left join             invoiceamtsummary ia                 on ia.guidinvoice = s.guidinvoice                   s.year = @targetyear          ,              s.month = @targetmonth      group              c.custid; 

Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -