gpt4 book ai didi

sql - 简单的 mysql group by query 需要帮助

转载 作者:行者123 更新时间:2023-11-29 04:59:41 25 4
gpt4 key购买 nike

当我添加显示的行时此查询失败...

Select Companyid, count(*) as cnt
from mytable
where State is not null
and cnt = 1 <------------------------- FAIL
group by CompanyID

有什么办法吗?

如果有帮助的话,这是一个冗长的背景......

我有一个单表查询。

这是表格的示例:

CompanyID, State
1,OH
1,IL
1,NY
2,IL
3,NY
3,OH
4,NY
5,CA
5,WA

我想要一个会返回如下内容的查询:

2,IL
4,NY

目前我有这个

Select Companyid, count(*) as cnt
from mytable
where State is not null
group by CompanyID

这为我提供了每家公司的记录数。

即:

1,3
2,1
3,2
4,1
5,2

现在我想将上面的列表过滤为只有一条结果的两条记录。

我尝试添加另一个 where 子句,但失败了:

Select Companyid, count(*) as cnt
from mytable
where State is not null
and cnt = 1 <-------------------- FAIL
group by CompanyID

最佳答案

您可以使用 Having 子句来限制在您的 Group By 中只出现一次的记录:

Select companyId, state
From mytable
Where state Is Not Null
Group By companyId
Having Count(*) = 1

关于sql - 简单的 mysql group by query 需要帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2721507/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com