码迷,mamicode.com
首页 > 数据库 > 详细

SQL交叉表

时间:2016-06-23 12:31:23      阅读:293      评论:0      收藏:0      [点我收藏+]

标签:

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

公司最近需要给订单表做一个数据汇总的功能,同事给到一个参考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。 

 

SQL交叉表

标签:

原文地址:http://www.cnblogs.com/Tangcy/p/5610069.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!