当前位置: 首页 > 图文教程 > 数据库 > MSSQL > mssql CASE,GROUP BY用法

MSSQL
四种方法在SQL Server数据库中成批导入数据
关于SQL Server数据库备份和恢复特性介绍
SQL Server 2005中数据库镜像的四个问题
SQL Server 2005代理服务应用软件组成
如何巧妙利用SQL Server的EXISTS结构
教你轻松学会SQL Server记录轮班的技巧
解析SQL Server中数据库快照的工作原理
使用SQL2000将现有代码作为Web服务提供
指导:SQL Server无日志恢复数据库
SQL Server 2005 Express混合模式登录设置
检测SQL Server是否有特洛伊木马
分布式DBA:SQL存储过程知识总结
在SQL Server 2008中安装安全审计
SQL Server 2005五个动态管理对象
用SQL Server事件探查器创建跟踪
讲解SQL Server数据库触发器的安全隐患
如何减少SQL Server死锁发生的情况
在SQL Server中使用索引的技巧
在SQL 2005中实现循环每一行做一定的操作
教你用压缩技术给SQL Server备份文件瘦身

MSSQL 中的 mssql CASE,GROUP BY用法


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-13   浏览: 137 ::
收藏到网摘: n/a

创建数据库并利用case和group by实现数据库的插入数据操作
复制代码 代码如下:

--create database dbTemp
use dbTemp
create table test
(
Pid int identity(1,1) not null primary key,
Years datetime,
IsFirstSixMonths int default(0), --0表示上半年1表示下半年--
TotalCome int
)
insert test
select '2007-1-1',0,50
union
select '2007-3-1',0,60
union
select '2007-12-1',1,80
union
select '2008-1-1',0,100
union
select '2008-12-1',1,100
select * from test
select convert(char(4),Years,120) as 'year',
IsFirstSixMonths=case when IsFirstSixMonths=0 then '上半年' when IsFirstSixMonths=1 then '下半年' END ,
sum(totalcome) as 'sum' from test
group by IsFirstSixMonths,convert(char(4),Years,120)

select convert(char(4),Years,120) as 'year',
IsFirstSixMonths=case when IsFirstSixMonths=0 then '上半年' ELSE '下半年' END ,
sum(totalcome) as 'sum' from test
group by IsFirstSixMonths,convert(char(4),Years,120)
--DROP DATABASE dbtemp

结果如下:
复制代码 代码如下:

2007 上半年 110
2007 下半年 80
2008 上半年 100
2008 下半年 100