加入收藏 | 设为首页 | 会员中心 | 我要投稿 辽源站长网 (https://www.0437zz.com/)- 云专线、云连接、智能数据、边缘计算、数据安全!
当前位置: 首页 > 营销 > 电子商务 > 正文

sqlServer中 分类报表sql技巧 ,很实用

发布时间:2018-09-13 18:19:03 所属栏目:电子商务 来源:站长网
导读:有表 tableA 如下:-----------------------------------------------------id, type , countNumber , countDate1A102005-02-01 21:23:342B82005-02-01 21:23:343C52005-02-01 21:23:344B42005-02-01 11:23:345C52005-02-01 22:23:346A112005-02-02 12:23:

有表 tableA 如下:-----------------------------------------------------id,    type ,   countNumber ,   countDate1 A 10  2005-02-01 21:23:342 B 8  2005-02-01 21:23:343 C 5  2005-02-01 21:23:344 B 4  2005-02-01 11:23:345 C 5  2005-02-01 22:23:346 A 11  2005-02-02 12:23:347 B 9  2005-02-02 14:23:348 C 8  2005-02-02 17:23:349 A 15  2005-02-02 19:23:3410 C 6  2005-02-02 04:23:3411 A 7  2005-02-03 1:23:3412 B 11  2005-02-03 2:23:3413 C 12  2005-02-03 5:23:34.......................

想要用一条语句生成如下的报表

日期   类型A 类型B 类型C 2005-02-01   10 12 10  2005-02-02   26 9 14  2005-02-03   7 11 12 

我用的是如下的sql语句:

SELECT  a.DATEFMT ,(select sum(*) from tableA where type='A' and convert(char(10),countDate,20)= a.DATEFMT) typeA ,(select sum(*) from tableA where type='B' and convert(char(10),countDate,20)= a.DATEFMT) typeB ,(select sum(*) from tableA where type='C' and convert(char(10),countDate,20)= a.DATEFMT) typeC

FROM ( SELECT convert(char(10),countDate,20) DATEFMT FROM tableA GROUP BY convert(char(10),countDate,20)) a

但是这条语句在sqlserver 上执行起来特别的慢,要很久(20多秒),tabelA 中有9万条数据. 而我在mySql(表中有2万条数据)上执行就快很多!

后来在论坛上看到高手这样写

select convert(char(10),countDate,20),typeA=sum(case type when A then CountNumber else 0 end),typeB=sum(case type when B then CountNumber else 0 end),typeC=sum(case type when C then CountNumber else 0 end)From tableAgroup by convert(char(10),countDate,20)

只用 1秒 不到!  唉! 厉害厉害!

(编辑:辽源站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读