Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server TSQL计数案例别名_Sql Server_Tsql_Count_Alias - Fatal编程技术网

Sql server TSQL计数案例别名

Sql server TSQL计数案例别名,sql-server,tsql,count,alias,Sql Server,Tsql,Count,Alias,早上好 我试图创建一个简单的count语句,当它返回count时,它会为每列显示一个别名 例如d=狗,c=猫,b=鸟 select animal, count(animal) from pets group by CASE when animal='d' then 'dog' when animal='c' then 'cat' when animal='b' then 'bird' else 'others' 目前它抛出了一个错误,没有按第一个动物分组,但当我把动物放在那里时,它会返回 d

早上好

我试图创建一个简单的count语句,当它返回count时,它会为每列显示一个别名

例如d=狗,c=猫,b=鸟

select animal, count(animal)
from pets
group by CASE
when animal='d' then 'dog'
when animal='c' then 'cat'
when animal='b' then 'bird'
else 'others'
目前它抛出了一个错误,没有按第一个动物分组,但当我把动物放在那里时,它会返回

 d  1
 c  3
 b  0
我想让它也显示出来

dog 1
cat 3
bird 0

您还需要添加
CASE
语句来更改
SELECT
中动物名称的字母。@AdamWenger谢谢您,第一次使用CASE!您使用的是什么版本的SQL Server?2005年、2008年、2012年?嘿,你能得到答案真是太好了——但一点解释会让它变得更好。别忘了,很多新手来到Stack Overflow,我们喜欢我们的新手离开,比他们来的时候受的教育更多。一些对你来说很明显的事情对他们来说可能不那么明显——所以解释一下你改变了什么以及为什么改变会让事情变得更好总是好的
select count(animal), 'Animals'=CASE
when animal='d' then 'dog'
when animal='c' then 'cat'
when animal='b' then 'bird'
else 'others'
from pets
group by CASE
when animal='d' then 'dog' 
when animal='c' then 'cat'
when animal='b' then 'bird'
else 'others'