SQL查询以按特定日期条件进行过滤
SQL Server Management Studio V17.7
问题:我正在寻找与以下视图相关的指南:当Admit_Status = 1或Admit_Status = 0时,如何选择Start_Date在定义的日期范围之间的记录,如下所示:
条件应类似于:如果准入状态= 1,则dbo.PT_ASSIGNMENT.START_DATE> =向ifnull dbo.PT_ADMISSION.TERMINATION_DATE推荐的日期,然后now()否则dbo.PT_ADMISSION.TERMINATION_DATE,或者如果准入状态= 0,则开始日期> = Referral_date到ifnull dbo.PT_ADMISSION.PROSPECT_TERM_DATE,然后now()else dbo.PT_ADMISSION.PROSPECT_TERM_DATE
我的SQL查询(视图)不包含上述问题:
SELECT dbo.RES_BASIC.RESOURCE_ID,
dbo.PT_ADMISSION.ADMISSION_ID,
dbo.PT_ASSIGNMENT.START_DATE,
(CASE PT_ADMISSION.PROSPECT_ADMIT_DATE WHEN NULL THEN PT_ADMISSION.ADMIT_DATE ELSE PT_ADMISSION.PROSPECT_ADMIT_DATE END) AS REFERRAL_DATE,
dbo.PT_ADMISSION.ADMIT_DATE,
dbo.PT_ADMISSION.PROSPECT_ADMIT_DATE,
dbo.PT_ADMISSION.PROSPECT_TERM_DATE,
dbo.PT_ADMISSION.TERMINATION_DATE,
CASE WHEN PT_ADMISSION.ADMIT_DATE IS NOT NULL THEN 1 ELSE 0 END AS ADMIT_STATUS,
dbo.PT_BASIC.PATIENT_CODE,
dbo.RES_BASIC.NAME_FULL
FROM dbo.PT_BASIC
INNER JOIN dbo.PT_STATUS
ON dbo.PT_BASIC.PATIENT_ID = dbo.PT_STATUS.PATIENT_ID
INNER JOIN dbo.A_PATIENT_STATUS
ON dbo.PT_STATUS.ADMIN_SET_ID = dbo.A_PATIENT_STATUS.ADMIN_SET_ID
AND dbo.PT_STATUS.STATUS_CODE = dbo.A_PATIENT_STATUS.STATUS_CODE
INNER JOIN dbo.O_DATASET
ON dbo.PT_BASIC.DATASET_ID = dbo.O_DATASET.DATASET_ID
INNER JOIN dbo.PT_ADMISSION
ON dbo.PT_BASIC.PATIENT_ID = dbo.PT_ADMISSION.PATIENT_ID
AND dbo.PT_STATUS.ADMISSION_ID = dbo.PT_ADMISSION.ADMISSION_ID
INNER JOIN dbo.PT_ASSIGNMENT
ON dbo.PT_BASIC.PATIENT_ID = dbo.PT_ASSIGNMENT.PATIENT_ID
INNER JOIN dbo.A_ASSIGNMENT_TYPE
ON dbo.PT_ASSIGNMENT.ADMIN_SET_ID = dbo.A_ASSIGNMENT_TYPE.ADMIN_SET_ID
AND dbo.PT_ASSIGNMENT.ASSIGNMENT_TYPE = dbo.A_ASSIGNMENT_TYPE.TYPE_ID
INNER JOIN dbo.RES_BASIC
ON dbo.PT_ASSIGNMENT.RESOURCE_ID = dbo.RES_BASIC.RESOURCE_ID
WHERE (dbo.O_DATASET.DATASET_NAME = 'XXXXXXXXXX')
AND (dbo.A_ASSIGNMENT_TYPE.DESCRIPTION = 'REFERRING PHYSICIAN')
GROUP BY dbo.RES_BASIC.NAME_FIRST + ' ' + dbo.RES_BASIC.NAME_LAST,
dbo.RES_BASIC.RESOURCE_ID,
dbo.PT_ADMISSION.ADMISSION_ID,
dbo.PT_BASIC.PATIENT_CODE,
dbo.PT_ASSIGNMENT.START_DATE,
dbo.PT_ADMISSION.PROSPECT_TERM_DATE,
dbo.PT_ADMISSION.PROSPECT_ADMIT_DATE,
dbo.PT_ADMISSION.TERMINATION_DATE,
dbo.PT_ADMISSION.ADMIT_DATE,
dbo.RES_BASIC.NAME_FULL
答案 0 :(得分:1)
您可以使用简单的AND和OR来将几乎所有“ if”放入条件中。
我很难在心理上解析您的“类似”部分,但要举一个通用的例子。
IF A THEN B ELSE C
可以翻译为(A AND B) OR (NOT A AND C)
注意:Bill Braskey的“评论”也值得考虑。如果条件逻辑变得足够复杂,则使用简单条件的数据库执行UNION查询的工作量可能会减少。您仍然需要其中一个条件为A AND B
,另一个条件为NOT A AND C
才能适当地应用条件,但是您需要从整体条件简化(尤其是考虑“ C”时)实际上可能是IF D THEN E ELSE F
的翻译。
答案 1 :(得分:0)
也许可以采取简单的方法,根据不同的要求编写两个查询并进行合并