添加另一个表

时间:2014-06-26 19:46:03

标签: sql-server where-clause

好的,所以我已经做了一份报告,计算了2014年内每个月有多少合同的资金。

所以现在我必须计算所有服务合同的总数。

我的意思是我有一个名为tlkOrigDept的表。在那张桌子里我有这个

  Table tlkOrigDept

  orig_dept_id         Orig_Dept_Name
      1                    Sales
      2                   Service
      3                    F&I
      4                   Other
      5                   Direct Marketing  

所以我必须从SERVICE获得所有资助的合同,即'orig_dept_id'= 2所以这是我的查询,但我看到的问题是在我的where子句中。因为当我将orig_dept_Id更改为3时它可以工作但不适用于2.它只显示空白而不是错误消息。

用户输入@Begin_date和@End_Date用户而不是选择@Program公司。用户应该看到每个月仅来自SERVICE的所有合同。

我在SELECT语句或我的WHERE子句中看到了问题

这是我的查询

[code="sql"]    

Alter Proc spGetAdminServiceYTD

 (@Begin_Date  DATETIME, 
  @End_Date DATETIME,
  @program int=null) As

 Declare @year int
 Set @year = 2014

 Declare @orig_dept_ID Int
 Set @orig_dept_ID = 2


  Begin


    SELECT  d.name, a.dealer_code, b.last_name, b.city, b.state, b.phone,e.orig_dept_name
        , COUNT(CASE WHEN  MONTH(c.orig_dept_id) = 1 THEN 1 ELSE NULL END) January
        , COUNT(CASE WHEN  MONTH(c.orig_dept_id) = 2 THEN 1 ELSE NULL END) Feburary
        , COUNT(CASE WHEN  MONTH(c.Funded_date) = 3 THEN 1 ELSE NULL END) March
        , COUNT(CASE WHEN  MONTH(c.Funded_date) = 4 THEN 1 ELSE NULL END) April
        , COUNT(CASE WHEN  MONTH(c.Funded_date) = 5 THEN 1 ELSE NULL END) May
        , COUNT(CASE WHEN  MONTH(c.Funded_date) = 6 THEN 1 ELSE NULL END) June
        , COUNT(CASE WHEN  MONTH(c.Funded_date) = 7 THEN 1 ELSE NULL END) July
        , COUNT(CASE WHEN  MONTH(c.Funded_date) = 8 THEN 1 ELSE NULL END) August
        , COUNT(CASE WHEN  MONTH(c.Funded_date) = 9 THEN 1 ELSE NULL END) September
        , COUNT(CASE WHEN  MONTH(c.Funded_date) = 10 THEN 1 ELSE NULL END) October
        , COUNT(CASE WHEN  MONTH(c.Funded_date) = 11 THEN 1 ELSE NULL END) November
        , COUNT(CASE WHEN  MONTH(c.Funded_date) = 12 THEN 1 ELSE NULL END) December
        , count(1) As YTD      




  FROM tdealer a 
         JOIN tContact b ON a.contact_id = b.contact_id 
         JOIN tContract c ON a.dealer_id = c.dealer_id 
         JOIN tCompany d ON c.company_id = d.company 
         JOIN tlkOrigDept E ON c.orig_dept_id = e.orig_dept_id 


  WHERE c.orig_dept_id = 2 
         And d.company_id = @program 
         AND c.Funded_date  >= DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE())-5, 0) 
         And YEAR(c.Funded_date) = @Year 
         And c.Funded_date < DATEADD(MONTH, DATEDIFF(MONTH, -1, GETDATE())-1, 0) 
         And (c.funded_date) between @Begin_Date And @End_Date 


   GROUP BY
    d.name,
    a.dealer_code,
    b.last_name,
    b.city,
    b.state,
    b.phone,
    MONTH(c.funded_date),
    Month(e.orig_dept_name),
    e.orig_dept_name
      end



    exec spGetAdminServiceYTD '01/01/2014', '05/30/2014', '47'

0 个答案:

没有答案