优化代码SELECT SUM(CASE WHEN order_date BETWEEN '2021-11-01' AND '2021-11-15' THEN 1 ELSE 0 END) AS new_customer_count, SUM(CASE WHEN order_date BETWEEN '2021-11-01' AND '2021-11-15' THEN amount ELSE 0 END) AS new_customer_amount, SUM(CASE WHEN order_date BETWEEN '2021-11-01' AND '2021-11-15' AND customer_id IN ( SELECT customer_id FROM orders WHERE order_date < '2020-11-01' ) THEN 1 ELSE 0 END) AS old_customer_count, SUM(CASE WHEN order_date BETWEEN '2021-11-01' AND '2021-11-15' AND customer_id IN ( SELECT customer_id FROM orders WHERE order_date < '2020-11-01' ) THEN amount ELSE 0 END) AS old_customer_amount FROM orders WHERE order_date BETWEEN '2021-11-01' AND '2021-11-15'
时间: 2024-01-24 21:18:03 浏览: 110
数据库实验2的实验报告1. 在 studentsdb 数据库中使用 SELECT 语句进行基本查询。 (1)在 student
5星 · 资源好评率100%
可以考虑使用JOIN语句代替子查询,这样可以避免在子查询中进行多次查询。同时,可以将CASE WHEN语句简化为IF函数,这样可以提高代码的可读性。具体优化后的代码如下所示:
SELECT
SUM(IF(order_date BETWEEN '2021-11-01' AND '2021-11-15', 1, 0)) AS new_customer_count,
SUM(IF(order_date BETWEEN '2021-11-01' AND '2021-11-15', amount, 0)) AS new_customer_amount,
SUM(IF(order_date BETWEEN '2021-11-01' AND '2021-11-15' AND o1.customer_id IS NOT NULL, 1, 0)) AS old_customer_count,
SUM(IF(order_date BETWEEN '2021-11-01' AND '2021-11-15' AND o1.customer_id IS NOT NULL, amount, 0)) AS old_customer_amount
FROM orders o
LEFT JOIN (
SELECT customer_id FROM orders WHERE order_date < '2020-11-01'
) o1
ON o.customer_id = o1.customer_id
WHERE order_date BETWEEN '2021-11-01' AND '2021-11-15'
阅读全文