计算某一列中另一列的值为 1 的行数

发布于 2024-11-29 12:18:42 字数 384 浏览 1 评论 0原文

我正在使用 select count unique 来计算列中的记录数。但是,我只想计算不同列的值为 1 的记录。

所以我的表看起来有点像这样:

Name------Type
abc---------1
def----------2
ghi----------2
jkl---------1
mno--------1

我希望查询仅计算 abc、jkl 和 mno,从而返回“3”。

我无法使用 CASE 函数执行此操作,因为这似乎仅适用于同一列中的条件。

编辑:抱歉,我应该添加,我想进行一个计算这两种类型的查询。 所以结果应该看起来更像: 1---3 2---2

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:

Name------Type
abc---------1
def----------2
ghi----------2
jkl-----------1
mno--------1

and I want the query only to count abc, jkl and mno and thus return '3'.

I wasn't able to do this with the CASE function, because this only seems to work with conditions in the same column.

EDIT: 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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

夏日浅笑〃 2024-12-06 12:18:42
SELECT COUNT(*) 
  FROM dbo.[table name] 
  WHERE [type] = 1;

如果您想按类型返回计数:

SELECT [type], COUNT(*)
  FROM dbo.[table name]
  GROUP BY [type]
  ORDER BY [type];

您应该避免使用 type 之类的关键字作为列名称 - 如果您使用更具体的非保留字,则可以避免使用大量方括号。

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.

勿忘初心 2024-12-06 12:18:42

我想你会想要(假设你不想计算 ('abc',1) 两次,如果它在你的表中两次):

select count(distinct name) 
  from mytable
 where type = 1

编辑:用于获取所有类型

select type, count(distinct name)
  from mytable
 group by type
 order by type

I think you'll want (assuming that you wouldn't want to count ('abc',1) twice if it is in your table twice):

select count(distinct name) 
  from mytable
 where type = 1

EDIT: for getting all types

select type, count(distinct name)
  from mytable
 group by type
 order by type
开始看清了 2024-12-06 12:18:42

从 tbl 中选择 count(1),其中 type = 1

select count(1) from tbl where type = 1

小耗子 2024-12-06 12:18:42
;WITH MyTable (Name, [Type]) AS
(
SELECT 'abc', 1
UNION
SELECT 'def', 2
UNION
SELECT 'ghi', 2
UNION
SELECT 'jkl', 1
UNION
SELECT 'mno', 1
) 
SELECT COUNT( DISTINCT Name)
FROM MyTable
WHERE [Type] = 1
;WITH MyTable (Name, [Type]) AS
(
SELECT 'abc', 1
UNION
SELECT 'def', 2
UNION
SELECT 'ghi', 2
UNION
SELECT 'jkl', 1
UNION
SELECT 'mno', 1
) 
SELECT COUNT( DISTINCT Name)
FROM MyTable
WHERE [Type] = 1
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文