读书人

关于SQL聚合函数请问

发布时间: 2012-02-12 17:16:33 作者: rapoo

关于SQL聚合函数请教
字段有两个:p_code(产品代号),p_status(产品状态)

declare @tb_product table (p_id int identity(1,1),p_code int,p_status int)
insert into @tb_product(p_code,p_status)
select '111 ', '1 ' union all
select '111 ', '2 ' union all
select '111 ', '2 ' union all
select '222 ', '1 ' union all
select '222 ', '2 ' union all
select '222 ', '1 '

想查的:以p_code分组
count(p_status)--所有状态的数量
count(p_status=2)--状态为2的数量

可以一条语句模块查出三列么?
p_code,count(p_status),count(p_status=2)
group by p_code

谢谢各位,费心了.

[解决办法]
select p_code,count(*),sum(case when p_status=2 then 1 else 0 end) from @tb_product group by p_code

读书人网 >SQL Server

热点推荐