在SQL Server中需要帮助以列出和计算动物的状态

时间:2018-01-28 08:24:03

标签: sql-server tsql

我需要一个SQL Server查询,我可以根据状态进行计数和分组,表格如下所示

name    status
---------------
frog    1
frog    0
frog    0
rabbit  0
rabbit  1
rabbit  0
rabbit  0

输出将是这样的:

name   status0   status1
-------------------------
frog   2         1
rabbit 3         1

谢谢!

2 个答案:

答案 0 :(得分:2)

试试这个:

Select name, 
       Count(Case When Status = 0 Then 1 Else Null End) AS Status0,
       Count(Case When Status = 1 Then 1 Else Null End) AS Status1
FROM TableName
Group By name

此处的主要注意事项是,Count聚合函数会忽略NULL个值并且不计算它们,这就是我们在Case Null中使用Else的原因部分!

答案 1 :(得分:1)

您也可以使用 render() { return ( <View style={commonStyles.container}> <List> <FlatList data={this.props.questions} renderItem={({ item }) => ( <ListItem roundAvatar title={'nicola'} /> )} /> </List> </View> ); }

PIVOT

结果:

DECLARE @T TABLE(name VARCHAR(10),   status INT)
INSERT INTO @T
VALUES
('frog',  1 ),
('frog',  0 ),
('frog',  0 ),
('rabbit',  0 ),
('rabbit',  1 ),
('rabbit',  0 ),
('rabbit',  0 )

SELECT name, [0] status0, [1] status1 FROM @T
    PIVOT(COUNT(status) FOR status IN ([0],[1])) PVT