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

MSSQL
使用SQL Server数据库嵌套子查询的方法
SQL Server SQL Agent服务使用教程小结
五种提高 SQL 性能的方法
非常不错的SQL语句学习手册实例版
SQL语言查询基础:连接查询 联合查询 代码
SQL SERVER的优化建议与方法
简单的SQL Server备份脚本代码
sql基本函数大全
SQL查询语句精华使用简要
数据库分页存储过程代码
SQL查询连续号码段的巧妙解法
sql server中千万数量级分页存储过程代码
sql2000各个版本区别总结
如何远程连接SQL Server数据库图文教程
一个SQL语句获得某人参与的帖子及在该帖得分总和
通用分页存储过程,源码共享,大家共同完善
SQL查找某一条记录的方法
使用 GUID 值来作为数据库行标识讲解
非常详细的SQL--JOIN之完全用法
收缩后对数据库的使用有影响吗?

MSSQL 中的 mssql CASE,GROUP BY用法


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-13   浏览: 67 ::
收藏到网摘: 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