SELECT lot_id, max(claim_time) claim_time, count( case when (open_category= 'Ship') then lot_id else null end ) as LS, COUNT( case when (ope_category = "Unship") then lot_id else null end ) as LUS FROM f3rpt.F3_TB_DAILY_FABOUT WHERE SUBSTR(lot_id,1,2) not in ('CA','CW','ES','EO','EM') AND lot_type ='Production' and lot_id not like 'H%' and SUBSTR(lot_id,7,4) = '.00F' and ope_category in ('Ship','Unship') and YEAR(claim_time) = YEAR(current date -1 days) and month(claim_time) = month (current date -1 days) group by lot_id 请优化下这条sql
时间: 2024-01-01 14:03:40 浏览: 164
这个 SQL 查询中有一些可以优化的地方,以下是优化建议:
1. 使用别名缩短代码长度并提高可读性。
2. 使用 EXISTS 或者 INNER JOIN 来代替子查询,以提高查询效率。
3. 使用 BETWEEN 来代替 YEAR 和 MONTH 函数的组合使用,以提高查询效率。
4. 使用 IN 来代替多个 OR 条件的组合使用,以提高查询效率。
5. 删除无用的 else null,简化代码。
优化后的 SQL 查询如下所示:
SELECT
lot_id,
MAX(claim_time) AS claim_time,
COUNT(CASE WHEN open_category = 'Ship' THEN lot_id END) AS LS,
COUNT(CASE WHEN ope_category = 'Unship' THEN lot_id END) AS LUS
FROM
f3rpt.F3_TB_DAILY_FABOUT t1
WHERE
SUBSTR(lot_id, 1, 2) NOT IN ('CA', 'CW', 'ES', 'EO', 'EM')
AND lot_type = 'Production'
AND lot_id NOT LIKE 'H%'
AND SUBSTR(lot_id, 7, 4) = '.00F'
AND ope_category IN ('Ship', 'Unship')
AND claim_time BETWEEN DATE('now', '-1 day', 'start of month') AND DATE('now', '-1 day', 'start of month', '+1 month', '-1 day')
GROUP BY
lot_id;
阅读全文