使用SQL Server中的某些条件获取日期

时间:2015-06-24 10:20:38

标签: sql-server

我想要的是EmployeeName表中的emp_mst,其中包含以下条件: -

  1. EmployeeName以及current date天内过去7个月的所有15
  2. 从下面的查询我得到了上个月的结果,但我想要过去6个月

    select DATEADD(month, -1, GETDATE()- 15)
    

    Version image

    我正在使用sql server 2008

    更新程序

    SELECT * FROM (SELECT CASE 
                     WHEN (SELECT Isnull(Sum(total_day), 0) 
                           FROM   xxacl_erp_ab_pl_count_view 
                           WHERE  emp_card_no = em.emp_card_no) > 7 THEN 
                     'DOC Exteded By 1 month. Reason:- Taken leave=' 
                     + CONVERT(VARCHAR, (SELECT Sum(total_day) FROM 
                     xxacl_erp_ab_pl_count_view 
                     WHERE emp_card_no = em.emp_card_no)) 
                     + 
    ' which is > 7. Actual DOC=' 
              + CONVERT(VARCHAR, Dateadd(mm, em.probation_period, em.date_of_joining), 103) 
              + '' 
              ELSE 'N/A' 
            END Remark, 
            em.* 
     FROM   emp_mst em 
            LEFT JOIN company_mst comp 
                   ON em.comp_mkey = comp.mkey 
                      AND comp.fa_year = 2008 
                      AND company_name NOT LIKE '%HELIK%' 
     WHERE  em.status IN ( 'A' ) --and em.emp_type='E' 
            AND em.emp_card_no != 9999 
            AND em.resig_date IS NULL 
            AND CONVERT(DATETIME, em.date_of_joining, 103) >= 
                CONVERT(DATETIME, 
                Dateadd(m, -6, Getdate()), 103) 
            AND em.emp_card_no NOT IN (SELECT emp_card_no 
                                       FROM   p_emp_confirmation_hdr 
                                       WHERE  delete_flag = 'N' 
                                              AND hr_flag = 'Y')) pp 
    WHERE  remark = 'N/A' 
    

2 个答案:

答案 0 :(得分:3)

转换为日期以避免使用时间戳进行计算

WHERE
  yourdate >= dateadd(m, -6, datediff(d, 15, getdate())) and 
  yourdate <  dateadd(d, -15, datediff(d, 0, getdate()))

使用sqlserver 2005或更早版本更改了为您调整的答案

在间隔期间增加了15天

答案 1 :(得分:1)

SELECT [emp_name] 
FROM [TABLE] 
WHERE [DateColumn] BETWEEN DATEADD(MONTH, -6, CAST(GETDATE() AS DATE)) 
    AND DATEADD(DAY, -15, CAST(GETDATE() AS DATE))

这将向您显示六个月前和15天前添加的员工,例如,今天运行的员工将为您提供2014-12-24和2015-06-09范围内的员工。

编辑:对于SQL Server 2005及更早版本:

SELECT [emp_name] 
FROM [TABLE] 
WHERE [DateColumn] BETWEEN DATEADD(MONTH, -6, cast(convert(char(11), getdate(), 113) as datetime)) 
    AND DATEADD(DAY, -15, cast(convert(char(11), getdate(), 113) as datetime))