帮忙写一个sql的分组语句

来源:百度知道 编辑:UC知道 时间:2024/05/25 14:54:40
我用的是sqlserver数据库
数据库中字段如下
id---t
01---s
01---s
01---d
01---d
假设t还有一个值q,但是数据库中没有该项,现在查询数据库已实现下面的效果(是根据id查询的哈):
s---d---q---total
2---2---0---2

备注:注意t的值,如果查询的id没有对应的t值是q的,则显示为0
该怎么做呢?不知道我说地清楚了不~呵呵,希望达人们帮我解决下。。谢谢
还要包括一种情况哈,就是当数据库中没有该ID号时,也是输出
s---d---q---total
0---0---0---0
这样的值,而不是什么都没有,呵呵。大家帮忙写个存储过程吧~谢谢了各位

select id,s,d,q,(s+d+q) as total from
(select id,sum(case when t='s' then 1 else 0 end) as s,
sum(case when t='d' then 1 else 0 end) as d,
sum(case when t='q' then 1 else 0 end) as q
from 表名 group by id) a
------------------补充---------
你补充的那个我用id=02的测试了一下,只能写到这种程度了
select isnull(sum(case when t='s' then 1 else 0 end),0) as s,
isnull(sum(case when t='d' then 1 else 0 end),0) as d,
isnull(sum(case when t='q' then 1 else 0 end),0) as q
from 表名 where id='02'

你上边的写错了吧?结果该是
2 2 0 4

select id,t,(select count(1) from table) p
from table

以一条语句作为该列就可以了,不知道我说的复合你的意思不?