简体   繁体   English

如何通过使用SQL Server 2005中的Select语句计算两个字段?

[英]How to count two fields by using Select statement in SQL Server 2005?

Total records in table are 10. 表中的总记录为10。

Select count(ID) from table1 where col1 = 1 (Result is 8)
Select count(ID) from table1 where col1 = 0 (Result is 2)

So its a same table but count is based on different condition. 因此,其表相同,但计数基于不同的条件。 How am i gonna get two results (counts) using one select statement? 我如何使用一个选择语句获得两个结果(计数)?

Also Performance is a big concern here. 在这里,性能也是一个大问题。

PS: I am using Stored procedure... PS:我正在使用存储过程...

EDIT: I wanna clear the above query is just a part of a big SP logic (for me at least). 编辑:我想清除上面的查询只是一个大SP逻辑的一部分(至少对我而言)。 Since i got these following answers, it gave another idea to achieve it in different way. 既然我得到了以下答案,它给了另一种以不同方式实现它的想法。 My above question is a bit changed now.....Please help here? 我上面的问题现在有点改变了.....请在这里帮助? Its a same col (bool type) with true or false state. 它是带有true或false状态的相同col(布尔类型)。

Use CASE: 使用案例:

SELECT
    SUM(CASE col1 WHEN 1 THEN 1 ELSE 0 END) AS Count1,
    SUM(CASE col1 WHEN 0 THEN 1 ELSE 0 END) AS Count0
FROM table1

您应该使用子选择或UNIONS,我看不到其他方式...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM