Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 查找具有GROUP BY和SUM的记录集_Sql_Group By_Aggregate Functions - Fatal编程技术网

Sql 查找具有GROUP BY和SUM的记录集

Sql 查找具有GROUP BY和SUM的记录集,sql,group-by,aggregate-functions,Sql,Group By,Aggregate Functions,我想查询每个GroupID(总是成对出现),其中HasData的两个条目的值都是1 |GroupID | HasData | |--------|---------| | 1 | 1 | | 1 | 1 | | 2 | 0 | | 2 | 1 | | 3 | 0 | | 3 | 0 | | 4 | 1 | | 4 | 1

我想查询每个GroupID(总是成对出现),其中HasData的两个条目的值都是1

|GroupID | HasData |
|--------|---------|
|  1     |  1      |
|  1     |  1      |
|  2     |  0      |
|  2     |  1      |
|  3     |  0      |
|  3     |  0      |
|  4     |  1      |
|  4     |  1      |
因此,结果将是:

1
4
这是我正在尝试的,但我似乎做得不对。每当我在GroupID上执行
分组方式时,我只能在选择器中访问该分组

选择GroupID
从桌子上
按组ID分组,HasData
具有总和(HasData)=2
但我得到以下错误消息,因为HasData确实有点错误:

Operand data type bit is invalid for sum operator.

如果两条记录都为真,我可以进行两次计数吗?

您可以使用
having
子句检查所有值是否为1:

select GroupId
from table
group by GroupId
having sum(cast(HasData as int)) = 2

也就是说,只需从
group by
列中删除
HasData
列,然后对其进行检查。

您可以使用
having
子句检查所有值是否为1:

select GroupId
from table
group by GroupId
having sum(cast(HasData as int)) = 2

也就是说,只需将
HasData
列从
groupby
列中删除,然后对其进行检查。

只需排除那些具有HasData=0的记录的组ID即可

select distinct a.groupID
from table1 a 
where not exists(select * from table1 b where b.HasData = 0 and b.groupID = a.groupID)

只需排除那些具有HasData=0的记录的组ID

select distinct a.groupID
from table1 a 
where not exists(select * from table1 b where b.HasData = 0 and b.groupID = a.groupID)
还有一个选择

SELECT GroupID
FROM table
WHERE HasData <> 0
GROUP BY GroupID
HAVING COUNT(*) > 1
选择GroupID
从桌子上
其中hasdata0
按组ID分组
计数(*)大于1的
还有一个选项

SELECT GroupID
FROM table
WHERE HasData <> 0
GROUP BY GroupID
HAVING COUNT(*) > 1
选择GroupID
从桌子上
其中hasdata0
按组ID分组
计数(*)大于1的

我不确定这三个答案中哪一个执行得最快,但将一个表映射到具有两个不同别名的表本身会得到很酷的分数和复选标记。谢谢大家,大家都投票!我不确定这三个答案中哪一个会表现得最快,但将一个表映射到具有两个不同别名的表本身会得到很酷的分数和复选标记。谢谢大家,大家都投票!