SQL交叉表

之前做货品横向展示时,有看到评论说用到交叉表。

公司最近需要给订单表做一个数据汇总的功能,同事给到一个参考SQL

select * from (select COUNT(1) as 已锁定 from tbl_order where orderLock = 1) as A,
(select COUNT(1) as 未锁定 from tbl_order where orderLock = 0) as B,
(select COUNT(1) as 未发货 from tbl_order where PushStatus=1 and statusid=14) as C,
(select COUNT(1) as 待发货 from tbl_order where PushStatus=1 and statusid=14 and isshipments=1) as D,
(select COUNT(1) as 已发货 from tbl_order where statusid=4) as E,
(select COUNT(1) as 未分配 from tbl_order where statusid = 14 and PushStatus<>3 and pushstatus=0) as F,
(select COUNT(1) as 已分配 from tbl_order where PushStatus=1) as G,
(select COUNT(1) as 已推送 from tbl_order where PushStatus=2) as H

 

看完改为下面SQL

SELECT
COUNT(CASE WHEN orderLock=1 THEN 1 ELSE NULL END) AS '已锁定',
COUNT(CASE WHEN orderLock=0 THEN 1 ELSE NULL END) AS '未锁定',
COUNT(CASE WHEN PushStatus=1 and statusid=14 THEN 1 ELSE NULL END) AS '未发货',
COUNT(CASE WHEN PushStatus=1 and statusid=14 and isshipments=1 THEN 1 ELSE NULL END) AS '待发货',
COUNT(CASE WHEN statusid=4 THEN 1 ELSE NULL END) AS '已发货',
COUNT(CASE WHEN statusid = 14 and PushStatus<>3 and pushstatus=0 THEN 1 ELSE NULL END) AS '未分配',
COUNT(CASE WHEN PushStatus=1 THEN 1 ELSE NULL END) AS '已分配',
COUNT(CASE WHEN PushStatus=2 THEN 1 ELSE NULL END) AS '已推送'
FROM tbl_order

与上面参考SQL相比只用到了一次查询表,并且如果有where条件更利于扩展。

直接上图 SQL执行计划参考:

 

 

 

 

 

 这个差距显而易见,欢迎大家提出更加优化的SQL。 

 

posted @ 2016-06-23 11:20  唐崇杨  阅读(1656)  评论(0编辑  收藏  举报