SQL交叉表

Posted Tony

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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。 

 

以上是关于SQL交叉表的主要内容,如果未能解决你的问题,请参考以下文章

SQL - 多行到列 - 枢轴?交叉表?

如何在sql中交叉连接两个表

将 Access 交叉表查询转换为 SQL Server

Access和/或SQL中的交叉表查询完成表组合

SQL Server-交叉联接内部联接基础回顾

带有Sum的Oracle SQL交叉表