求一个查询语句的优化,谢谢各位了!
下面的这个查询语句写的不是很理想,查询六千多条数据要3秒多钟,想请各位帮我优化一下,谢谢了!
SELECT 'x' AS pjlx ,
lszh ,
spdm ,
dwdm = ( CASE WHEN SUBSTRING(dwdm, 1, 3) = 'YF' THEN 'AA-23'
ELSE dwdm
END ) ,
dwmc ,
mxjls ,
xcljls ,
kcsjls ,
zhsmsj ,
zfbz = ( CASE WHEN minclbz < -1 THEN 'y'
ELSE 'n'
END ) ,
xclbz = ( CASE WHEN xcljls > 0 THEN 'y'
ELSE 'n'
END ) ,
kcsbz = ( CASE WHEN smlxs = 1
AND kcsjls > 0
AND kcsjls = xcljls THEN 'y'
ELSE 'n'
END ) ,
smlx = ( CASE WHEN smlxs = 1
AND maxsmlx IN ( '销售出库', '退货入库', '抽检出库', '销毁出库' )
THEN maxsmlx
ELSE '待定'
END )
FROM ( SELECT lszh ,
spdm ,
dwdm ,
dwmc ,
MAX(smsj) AS zhsmsj ,
MAX(ISNULL(smlx, '')) AS maxsmlx ,
MIN(ISNULL(clbz, 0)) AS minclbz ,
COUNT(*) AS mxjls ,
COUNT(CASE WHEN ISNULL(clbz, 0) IN ( 0, 1, 2 ) THEN lszh
ELSE NULL
END) AS xcljls ,
COUNT(CASE WHEN ISNULL(clbz, 0) = 2
AND ISNULL(smlx, '') IN ( '销售出库', '退货入库',
'抽检出库', '销毁出库' )
THEN lszh
ELSE NULL
END) AS kcsjls ,
COUNT(DISTINCT ( CASE WHEN ISNULL(clbz, 0) < 0 THEN NULL
ELSE ISNULL(smlx, '')
END )) AS smlxs
FROM lspy_jj_wlspy WITH ( NOLOCK )
WHERE lszh NOT IN (
SELECT lszh
FROM ( SELECT DISTINCT
lszh ,
--spdm ,
--dwdm ,
--dwmc ,
kzbz = ( CASE WHEN ISNULL(spdm, '') = ''
OR ISNULL(dwdm, '') = ''
OR ISNULL(dwmc, '') = ''
THEN 1
ELSE 0
END )
FROM lspy_jj_wlspy WITH ( NOLOCK )
WHERE ISNULL(clbz, 0) >= 0
) x
GROUP BY lszh
HAVING ( COUNT(*) > 1
OR MAX(kzbz) = 1
) )
GROUP BY lszh ,
spdm ,
dwdm ,
dwmc
HAVING MAX(smsj) < CONVERT(VARCHAR(10), GETDATE(), 126)
) y