5

我有一张桌子,假设它有四列 Id, Name, Cell_no, Cat_id。我需要返回计数Cat_id大于的所有列1

该组应该在Cell_no和上完成Name。到目前为止我做了什么..

select Cell_no, COUNT(Cat_id)
from TableName
group by Cell_Number
having COUNT(Cat_id) > 1

但我需要的是这样的东西。

select * 
from TableName
group by Cell_Number
having COUNT(Cat_id) > 1
4

3 回答 3

2

Pratik's answer is good but rather than using the IN operator (which only works for single values) you will need to JOIN back to the result set like this

SELECT t.* 
FROM tableName t
INNER JOIN      
    (SELECT Cell_no, Name 
    FROM TableName
    GROUP BY Cell_no , Name
    HAVING COUNT(Cat_id) > 1) filter
    ON t.Cell_no = filter.Cell_no AND t.Name = filter.Name
于 2012-05-28T06:39:48.620 回答
1

您只需要修改您的查询,如下所示 -

select * from tableName where (Cell_no, Name) in (
          select Cell_no, Name from TableName
           Group by Cell_no , Name
           having COUNT(Cat_id) > 1
           )

如问题所问,您想按 Cell_no 和 Name 进行分组。如果是这样,您需要更改对按列分组的查询并选择部分..正如我所提到的

于 2012-05-28T06:28:50.553 回答
1

这个版本只需要对数据进行一次传递:

SELECT *
FROM   (SELECT a.*
              ,COUNT(cat_id) OVER (PARTITION BY cell_no)
               AS count_cat_id_not_null
        FROM   TableName a)
WHERE  count_cat_id_not_null > 1;
于 2012-05-28T06:32:42.540 回答