现在的位置: 首页 > 综合 > 正文

关于SQL分组统计

2012年09月09日 ⁄ 综合 ⁄ 共 795字 ⁄ 字号 评论关闭
关于SQL分组统计

我想做一个分组统计,按人员分组 字段名为pname, 然后统计每个提出过多少问题,已经解决多少个问题,未解

决多少个问题, 表中4个字段 ID,pname,question,decide 第一个字段是ID,第二个字段是人名,第三个字段是

这个人提的问题,第4个字段是问题是否解决是个标志字段,"y"就是解决了 "n"就是没解决 ,现在我想统计每个

人都提了多少问题,其中解决多少,没解决多少? 请大虾门 帮帮忙.

使用case

select pname,count(*) as 提问数量,sum(case decide when 'y' then 1 else 0 end) as 已解决数量,sum

(case decide when 'n' then 1 else 0 end) as 没解决数量
from 表
group by pname

isnull可以将null值替换

下面的示例为 titles 表中的所有书选择书名、类型及价格。如果一个书名的价格是 NULL,那么在结果集中

显示的价格为 0.00。
USE pubs
GO
SELECT SUBSTRING(title, 1, 15) AS Title, type AS Type,
ISNULL(price, 0.00) AS Price
FROM titles
GO
下面是结果集:
Title Type Price
--------------- ------------ --------------------------
The Busy Execut business 19.99
Cooking with Co business 11.95
You Can Combat business 2.99
Straight Talk A business 19.99
Silicon Valley mod_cook 19.99
The Gourmet Mic mod_cook 2.99
The Psychology UNDECIDED

Count 函数不统计包含 Null 字段的记录,除非 expr 是星号 (*) 通配符。

抱歉!评论已关闭.