计算各列的值

时间:2014-01-08 08:52:03

标签: sql-server-2008

我有一张桌子

school code   school_name subcode1 subcode2 subcode3 
001               xyz      56        55     54
002               abc      55        56     54
003               xyz      54        55     56

假设56 =英语或55 =印地文,我想检查学校xyz是否有多少英语科目或有多少印地语科目等。

我在条件如下使用了count(*)函数:

select count(*) 
from schooltable 
where (subcode1 = '55' or subcode2 = '55' or subcode3 = 55) 
  and school_name='abc' 

但是它只给出了我想要的所有记录的所有记录,并希望像这样插入

scode schoolname sub   sub    sub
                 eng  hindi  history
001     abc      3      2      3

需要帮助。

2 个答案:

答案 0 :(得分:0)

你可以做一个条件总和,像这样

select sum(case when subcode1='55' or subcode2='55' or subcode3=55 then 1 else 0 end) as hindi,
       sum(case when subcode1='56' or subcode2='56' or subcode3=56 then 1 else 0 end) as english
from schooltable 
--where school_name='abc'    (not sure if you really require this constraint, although you have it in your question)

如果需要,您可以添加GROUP BY子句,但这取决于您的确切要求,数据库结构,主键等。但上述内容至少应该让您开始。

答案 1 :(得分:0)

试试这个,

select school_name,count(*) as TotalSub from schooltable
  group by school_name, subcode1,subcode2,subcode3
  having school_name = 'abc'