使用SQL查询查找输出

时间:2015-07-17 06:47:32

标签: sql-server

如果您想确保获得范围内的所有日期,如果范围值为'2015-07-01' and '2015-07-17'但我们得到的输出

Mr.Akbar Thekkan Thiruthinmel Mohammed Kutty    PATHOLOGY   12/12/2021  24/06/2016  24/06/2016  17/07/2015  17/07/2015  07/06/2016
Mr.Arif Gullu Muhammed                          PATHOLOGY   13/06/2022  18/10/2016  18/10/2016  16/07/2015  16/07/2015  26/09/2016
Mr.Rafeek Kuzhikkal                             PATHOLOGY   18/09/2021  12/08/2015  12/08/2015  17/07/2015  17/07/2015  30/06/2015
Ms.Marie Ann Taguran Calog                      PATHOLOGY   09/05/2017  13/12/2016  13/12/2016  16/07/2015  16/07/2015  22/11/2016
Ms.Shameema Saud Rafeeq                         PATHOLOGY   16/07/2015  16/07/2015  16/07/2015  16/07/2015  16/07/2015  16/07/2015
Ms.Thresiamma Royi                              NURSE       15/10/2017  09/04/2016  04/04/2016  16/07/2015  16/07/2015  16/07/2015
Ms.Zahara Beegum                                PATHOLOGY   16/07/2015  16/07/2015  16/07/2015  16/07/2015  16/07/2015  16/07/2015

查询:

select * 
from dbo.tblEmpMaster E 
left outer join tblDepartment D on e.emp_Deptid = D.Id
where 
    E.emp_PassExpDate between '2015-07-01' and '2015-07-17'
    or (E.emp_VisaExpDate between '2015-07-01' and '2015-07-17') 
    or (E.emp_EmiratesExp between '2015-07-01' and '2015-07-17')
    or (E.emp_MOHExpDate between '2015-07-01' and '2015-07-17')
    or (E.emp_MalInsExp between '2015-07-01' and '2015-07-17' )
    or (E.emp_LbrCardDate between '2015-07-01' and '2015-07-17')

1 个答案:

答案 0 :(得分:0)

如果要检索确切范围内的所有日期,请使用AND代替OR。尝试使用:

select * 
from dbo.tblEmpMaster E 
left outer join tblDepartment D on e.emp_Deptid = D.Id
where 
       (E.emp_PassExpDate between '2015-07-01' and '2015-07-17')
    and(E.emp_VisaExpDate between '2015-07-01' and '2015-07-17') 
    and(E.emp_EmiratesExp between '2015-07-01' and '2015-07-17')
    and(E.emp_MOHExpDate between '2015-07-01' and '2015-07-17')
    and(E.emp_MalInsExp between '2015-07-01' and '2015-07-17' )
    and(E.emp_LbrCardDate between '2015-07-01' and '2015-07-17')

示例数据:

CREATE TABLE #t1
(
    date1 date,
    date2 date,
    date3 date
)
INSERT INTO #t1 VALUES
('2015-02-03', '2015-02-04', '2015-02-05'),
('2015-01-03', '2015-02-05', '2015-02-06'),
('2015-02-07', '2015-02-08', '2015-02-09')

SELECT * FROM #t1
WHERE (date1 between '2015-02-01' and '2015-02-27')
      and (date2 between '2015-02-01' and '2015-02-27')
      and (date3 between '2015-02-01' and '2015-02-27')

DROP TABLE #t1

您可以尝试演示 的 SQL FIDDLE