计算不同列的值为1的列的行 [英] Counting the rows of a column where the value of a different column is 1
问题描述
我使用 select count distinct
来计算列中的记录数。但是,我只想计算不同列的值为1的记录。
I am using a select count distinct
to count the number of records in a column. However, I only want to count the records where the value of a different column is 1.
所以我的表看起来有点像这样:
So my table looks a bit like this:
名称------类型
abc --------- 1
def- --------- 2
ghi ---------- 2
jkl ----------- 1 < br>
mno -------- 1
Name------Type
abc---------1
def----------2
ghi----------2
jkl-----------1
mno--------1
并且我希望查询只计算abc,jkl和mno,因此返回'3'。
and I want the query only to count abc, jkl and mno and thus return '3'.
我无法用CASE函数做到这一点,因为这似乎只适用于同一列的条件。
I wasn't able to do this with the CASE function, because this only seems to work with conditions in the same column.
编辑:对不起,我应该添加,我想做一个查询计算两种类型。
所以结果应该看起来更像:
1 --- 3
2 --- 2
Sorry, I should have added, I want to make a query that counts both types. So the result should look more like: 1---3 2---2
推荐答案
SELECT COUNT(*)
FROM dbo.[table name]
WHERE [type] = 1;
如果要按类型返回计数:
If you want to return the counts by type:
SELECT [type], COUNT(*)
FROM dbo.[table name]
GROUP BY [type]
ORDER BY [type];
您应避免使用类型等关键字作为列名称 - 如果您使用更具体的非保留字。
You should avoid using keywords like type as column names - you can avoid a lot of square brackets if you use a more specific, non-reserved word.
这篇关于计算不同列的值为1的列的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!