如何用SQL语句创建这样一个视图?

有一张基础数据表 字段为 dept_code (部门代码) status (状态代码(1,2,3) ) ,这两个字段都不唯一,都是多条的。
想建立一个视图,统计以部门为单位 状态为1的有多少条, 为2 的有多少条, 为3的有多少条 ,
统计视图字段: dept_code (唯一) ; status=1的数量 ; status=2的数量 ; status=3的数量;

第1个回答  2015-03-10
你试试下面的SQL能不能在SQL里跑,再去试试创建视图:
select dept_code,status,count(1)
from table (你的表名)
group by dept_code,status追问

我的问题可能更复杂,是需要在最终的视图中 统计出 每个部门(相同dept_code)中状态为1,2,3的 分别有多少条
部门 状态1 状态2 状态3
aa 1 2 2
bb 3 2 1

追答

不好意思看到的晚了,你的需求可能会用到行列转换,给你个参考,应该有更好的写法:)

select
dept_code,
max(case status when 1 then qty end ) as status1,
max(case status when 2 then qty end ) as status2,
max(case status when 3 then qty end ) as status3
from
(
select dept_code,status,count(1) as qty
from U_Table
group by dept_code,status
) U_Table1
group by dept_code

本回答被网友采纳
相似回答