当前位置: 代码迷 >> Sql Server >> 求大神相助写出这个sql(统计-按天按月按年)
  详细解决方案

求大神相助写出这个sql(统计-按天按月按年)

热度:82   发布时间:2016-04-27 11:56:26.0
求大神帮助写出这个sql(统计-按天按月按年)
预约表 CGA_subscribe

英文列名 中文列名 数据类型 长度 允许空 默认值 字段说明
id 序号 VARCHAR 36 PK 主键 UUID
name 预约名称 VARCHAR 36 否
orderType 预约渠道 int 0 网上预约1 电话预约2 现场预约
orderTime 预约时间 VARCHAR 30 否 2012-05-01-1(1上午 2下午)



  | | | |
  | |变成如下表| |
  | | | |
  V V V V
---------------------

预约情况 按天 按月 按年
现场预约数 300 400 500
电话预约数 1000 1200 1500
网上预约数 500 600 700
总数 1800 2200 2700

---------------------




PS:求大神们帮助,跪谢..~尽快哦,在线等.

------解决方案--------------------
SQL code
------------------------------ Author  :fredrickhu(小F,向高手学习)-- Date    :2012-07-18 15:01:02-- Version:--      Microsoft SQL Server 2008 R2 (RTM) - 10.50.1617.0 (Intel X86) --    Apr 22 2011 11:57:00 --    Copyright (c) Microsoft Corporation--    Enterprise Edition on Windows NT 6.1 <X64> (Build 7600: ) (WOW64)--------------------------------> 测试数据:[tb]if object_id('[tb]') is not null drop table [tb]go create table [tb]([id] int,[name] varchar(14),[ordertype] int,[ordertime] datetime)insert [tb]select 1,'某公司的预约',0,'2012-5-29' union allselect 2,'某个人的预约',1,'2012-5-30' union allselect 3,'某集团1的预约',0,'2012-5-31' union allselect 4,'某集团2的预约',1,'2012-6-1' union allselect 5,'某集团3的预约',1,'2012-6-2' union allselect 6,'某集团4的预约',1,'2012-6-3' union allselect 7,'某集团5的预约',1,'2012-6-4' union allselect 8,'某集团6的预约',1,'2012-6-5' union allselect 9,'某集团7的预约',0,'2012-6-6' union allselect 10,'某集团8的预约',0,'2012-6-7' union allselect 11,'某集团9的预约',0,'2012-6-8' union allselect 12,'某集团10的预约',2,'2012-6-2' union allselect 13,'某集团11的预约',2,'2012-6-12' union allselect 14,'某集团12的预约',2,'2012-6-12'--------------开始查询--------------------------select  isnull((case when ordertype=2 then '现场预约' when ordertype=1 then '电话预约' when ordertype=0 then '网上预约' else null end) ,'总数') as 预约情况,  sum(case when datediff(dd,orderTime,getdate())=0 then 1 else 0 end) as 按天,  sum(case when datediff(mm,orderTime,getdate())=0 then 1 else 0 end) as 按月,  sum(case when datediff(yy,orderTime,getdate())=0 then 1 else 0 end) as 按年from  tbgroup by  isnull((case when ordertype=2 then '现场预约' when ordertype=1 then '电话预约' when ordertype=0 then '网上预约' end) ,'总数')with rollup----------------结果----------------------------/* 预约情况     按天          按月          按年-------- ----------- ----------- -----------电话预约     0           0           6网上预约     0           0           5现场预约     0           0           3NULL     0           0           14(4 行受影响)*/
  相关解决方案