select id,storename,Case type when 1 then '总部'else StoreCode end as StoreCode,type,Province,City,county,address,telephone,legal,(select count(number) from repair_order_hdr where (storeid=repair_store.ID or tostoreid=repair_store.ID) and status in(3,4,5))as ornum,(select count(number) from repair_order_hdr where (storeid=repair_store.ID or tostoreid=repair_store.ID) and status in(10))as sumnum,(select CASE ISNULL(SUM(Score)/Count(Score),0) WHEN 0 THEN 5 ELSE Round(convert(float,SUM(Score))/convert(float,Count(Score)),2) END from repair_order_hdr where (storeid=repair_store.ID or tostoreid=repair_store.ID) and Score>0)as score from repair_store where status=0 and type<>0 order by type,Province,city,county
时间: 2024-04-11 09:27:19 浏览: 98
为了优化这个 SQL 查询语句,我们可以采取以下几个步骤:
1. 减少子查询的数量:在原始的查询中,使用了三个子查询来计算 `ornum`、`sumnum` 和 `score`。我们可以将这些子查询转换为连接查询,以减少查询的复杂度和提高性能。
2. 使用 JOIN 语句:将 `repair_order_hdr` 表与 `repair_store` 表进行连接,使用连接查询来获取相关的统计信息。
3. 使用 CASE 语句:将原始的 CASE 语句进行简化,使其更加清晰易读。
优化后的 SQL 查询语句如下所示:
```sql
SELECT
rs.id,
rs.storename,
CASE rs.type WHEN 1 THEN '总部' ELSE rs.storecode END AS StoreCode,
rs.type,
rs.province,
rs.city,
rs.county,
rs.address,
rs.telephone,
rs.legal,
COUNT(CASE WHEN roh.status IN (3, 4, 5) THEN roh.number END) AS ornum,
COUNT(CASE WHEN roh.status = 10 THEN roh.number END) AS sumnum,
CASE WHEN ISNULL(SUM(roh.score) / COUNT(roh.score), 0) = 0 THEN 5 ELSE ROUND(CONVERT(FLOAT, SUM(roh.score)) / CONVERT(FLOAT, COUNT(roh.score)), 2) END AS score
FROM
repair_store rs
LEFT JOIN
repair_order_hdr roh ON rs.id = roh.storeid OR rs.id = roh.tostoreid
WHERE
rs.status = 0 AND rs.type <> 0
GROUP BY
rs.id,
rs.storename,
rs.type,
rs.province,
rs.city,
rs.county,
rs.address,
rs.telephone,
rs.legal
ORDER BY
rs.type,
rs.province,
rs.city,
rs.county;
```
通过使用连接查询和简化 CASE 语句,我们可以提高查询的执行效率和可读性。请注意,根据你的具体情况,可能还需要根据索引、数据量等因素进行进一步的优化。
阅读全文