Sql server 2008 各列的计数值
我有一张桌子Sql server 2008 各列的计数值,sql-server-2008,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学校有多少英语科目或多少印地语科目等 我在以下情况
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
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)
需要帮助。您可以进行条件求和,类似这样的操作
scode schoolname sub sub sub
eng hindi history
001 abc 3 2 3
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)
如果需要,您可以添加一个GROUPBY子句,但这取决于您的确切需求、数据库结构、主键等。但以上内容至少可以让您开始学习。试试这个
select school_name,count(*) as TotalSub from schooltable
group by school_name, subcode1,subcode2,subcode3
having school_name = 'abc'
“school code”是主键吗?你想在“school_name”上分组吗?我想OP想要的是按学校名称分组。OP也有where子句。没有WHERE子句或GROUPBY看起来更有意义,但这是OP在他的问题中所做的。我相信他主要对条件和部分感兴趣。