select * from ( SELECT P.PATIENT_ID, P.VISIT_ID, PM.NAME, PM.SEX, P.ADMISSION_DATE_TIME, ( SELECT TOP 1 DP.DEPT_NAME FROM DEPT_DICT DP WHERE DP.DEPT_CODE = P.DEPT_ADMISSION_TO ) AS DEPT_ADM, P.DISCHARGE_DATE_TIME, ( SELECT TOP 1 DP.DEPT_NAME FROM DEPT_DICT DP WHERE DP.DEPT_CODE = P.DEPT_DISCHARGE_FROM ) AS DEPT_DIS, DATEDIFF( DAY, P.ADMISSION_DATE_TIME, P.DISCHARGE_DATE_TIME ) AS INPAT_DAYS, P.DOCTOR_IN_CHARGE --datediff(day, P.ADMISSION_DATE_TIME,P.DISCHARGE_DATE_TIME) as zyts FROM PAT_VISIT P INNER JOIN PAT_MASTER_INDEX PM ON PM.PATIENT_ID = P.PATIENT_ID WHERE select * from ( SELECT P.PATIENT_ID, P.VISIT_ID, PM.NAME, PM.SEX, P.ADMISSION_DATE_TIME, ( SELECT TOP 1 DP.DEPT_NAME FROM DEPT_DICT DP WHERE DP.DEPT_CODE = P.DEPT_ADMISSION_TO ) AS DEPT_ADM, P.DISCHARGE_DATE_TIME, ( SELECT TOP 1 DP.DEPT_NAME FROM DEPT_DICT DP WHERE DP.DEPT_CODE = P.DEPT_DISCHARGE_FROM ) AS DEPT_DIS, DATEDIFF( DAY, P.ADMISSION_DATE_TIME, P.DISCHARGE_DATE_TIME ) AS INPAT_DAYS, P.DOCTOR_IN_CHARGE --datediff(day, P.ADMISSION_DATE_TIME,P.DISCHARGE_DATE_TIME) as zyts FROM PAT_VISIT P INNER JOIN PAT_MASTER_INDEX PM ON PM.PATIENT_ID = P.PATIENT_ID WHERE P.DISCHARGE_DATE_TIME >= '2016-01-01' AND P.DISCHARGE_DATE_TIME < = '2023-07-10' AND DATEDIFF( DAY,P.ADMISSION_DATE_TIME, P.DISCHARGE_DATE_TIME ) >= 30 ) t order by inpat_days desc P.DISCHARGE_DATE_TIME >= '2016-01-01' AND P.DISCHARGE_DATE_TIME < = '2023-07-10' AND DATEDIFF( DAY,P.ADMISSION_DATE_TIME, P.DISCHARGE_DATE_TIME ) >= 30 ) t order by inpat_days desc 帮我把这段sql优化一下
时间: 2023-09-23 17:13:18 浏览: 125
这段 SQL 查询语句可以进行一些优化,例如使用表别名、避免多次嵌套子查询等。下面是优化后的 SQL 查询语句:
```sql
SELECT
P.PATIENT_ID,
P.VISIT_ID,
PM.NAME,
PM.SEX,
P.ADMISSION_DATE_TIME,
DP_ADM.DEPT_NAME AS DEPT_ADM,
P.DISCHARGE_DATE_TIME,
DP_DIS.DEPT_NAME AS DEPT_DIS,
DATEDIFF(DAY, P.ADMISSION_DATE_TIME, P.DISCHARGE_DATE_TIME) AS INPAT_DAYS,
P.DOCTOR_IN_CHARGE
FROM
PAT_VISIT P
INNER JOIN PAT_MASTER_INDEX PM ON PM.PATIENT_ID = P.PATIENT_ID
LEFT JOIN DEPT_DICT DP_ADM ON DP_ADM.DEPT_CODE = P.DEPT_ADMISSION_TO
LEFT JOIN DEPT_DICT DP_DIS ON DP_DIS.DEPT_CODE = P.DEPT_DISCHARGE_FROM
WHERE
P.DISCHARGE_DATE_TIME >= '2016-01-01'
AND P.DISCHARGE_DATE_TIME <= '2023-07-10'
AND DATEDIFF(DAY, P.ADMISSION_DATE_TIME, P.DISCHARGE_DATE_TIME) >= 30
ORDER BY
INPAT_DAYS DESC;
```
此优化后的查询使用了表别名,将子查询转换为了左连接,并通过 JOIN 操作将 DEPT_DICT 表连接到主查询中,以减少子查询的数量。同时,将过滤条件放在 WHERE 子句中,使用了统一的日期格式。
请注意,优化 SQL 语句时需要考虑数据库的具体情况和索引的使用,这只是一个基本的优化示例,具体优化策略可能需要根据实际情况进行调整。
阅读全文