简体   繁体   English

如何使用where子句计算多个列? (SQL)

[英]How do I count more than one column with a where clause? (SQL)

I have the following query: 我有以下查询:

    SELECT count(Committees)
    FROM [Annual Questionnaire]
    WHERE Committees=TRUE;

However, I'd like to include other columns in the result eg Insurance, Equalities and counted where the value is True eg Insurance=True. 但是,我想在结果中包括其他列,例如“保险”,“平等”,并在值为True的地方计数,例如Insurance = True。 Not all the columns in the table have to be counted. 并非表中的所有列都必须计数。

I think a pseudo query would be: 我认为伪查询将是:

SELECT count(Committees),
       count(Insurance)
FROM [Annual Questionnaire]
WHERE Committees=TRUE
  AND Insurance=TRUE;

^ This doesn't work because it selects rows where only Committees and Insurance is True ^这行不通,因为它选择了只有委员会和保险为真的行

Basically, how do I count the specified columns where the value is True? 基本上,我该如何计算值为True的指定列?

you can do something like 你可以做类似的事情

SELECT 
    SUM(IIF(Committees=True, 1, 0))
    , SUM(IIF(Insurance=True, 1, 0))
FROM [Annual Questionnaire]

If you specify both in your WHERE clause, it will only return rows that have both columns true. 如果在WHERE子句中同时指定了两者,则只会返回列都为true的行。 Remember that the order of execution is the Where clause been executed before the Select, so it will filter down the data based on what you have and then select whatever you told it to select. 请记住,执行顺序是在Select之前执行Where子句的,因此它将根据您所拥有的内容过滤数据,然后选择您告诉其选择的内容。

This is the order of execution: 这是执行顺序:

FROM clause
WHERE clause
GROUP BY clause
HAVING clause
SELECT clause
ORDER BY clause 

There are similar threads already: How to get multiple counts with one SQL query? 已经有类似的线程: 如何通过一个SQL查询获得多个计数?

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

相关问题 SQL WHERE 子句从多个列中过滤 - SQL WHERE clause filter from more than one column 如何在sql中执行where子句并返回计数? - How do I do a where clause in sql and return a count back? 如何计算 SQL 服务器中带有 where 子句的行数? - How do I count the rows with a where clause in SQL Server? 如何在不止一列上计算差异 - How to COUNT DISTINCT on more than one column 在 SQL 中,如何在列 SQL 中执行计数相同的值,另外 5 列不在 GROUP BY 子句中? - In SQL how to do a Count Same values in a column SQL with 5 more columns not in GROUP BY clause? SQL查询返回同一行的多个副本,如果遇到多个where子句 - SQL query to return more than one copy of same row, if hit on more than one where clause 在 SQL 服务器 XML 列中,我如何验证相同的值是否存在于多行中 - In SQL Server XML column how do I verify whether same value is present in more than one rows or not 如何返回一种以上类型的行? - How do I return rows where there is more than one type? 我想写一个SQL查询具有计数功能的一列也有where子句 - I want to write an sql query having count function on one column also having where clause with like 带WHERE子句的COUNT比没有WHERE子句提供更多行 - COUNT with WHERE clause giving more rows than without WHERE clause
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM