扩展查询以包括父ID

时间:2018-10-31 16:26:24

标签: sql sql-server

我有以下SQL语句-

Intent main_act= new Intent(app.this,main_activity.class);
startActivity(main_act);

这很有效,并带来了以下结果-

SELECT
    gen_id, gen_name, COUNT(*)
FROM
    table
WHERE
  parent_id in (1,2,3,4)
GROUP BY
    gen_id, gen_name
HAVING 
    COUNT(*) > 1

我的问题是,我可以确定上述结果中唯一的一个是 test2 ,因为它具有所有四个 parent_id的的计数。如何修改SQL以返回结果集,从而可以查看哪些父ID属于哪个gen_id。

结果类似-

+--------+----------+------------------+
| gen_id | gen_name | (No column name) |
+--------+----------+------------------+
|      1 | test1    |                2 |
|      2 | test2    |                4 |
|      6 | test6    |                2 |
|      9 | test9    |                2 |
+--------+----------+------------------+

2 个答案:

答案 0 :(得分:4)

使用它的一种方法是使用

SELECT
    gen_id, gen_name, parent_id
FROM
    table AS t0
WHERE
  parent_id in (1,2,3,4)
AND EXISTS
(
    SELECT 1
    FROM table AS t1
    WHERE t0.gen_Id = t1.gen_id
    AND t0.parent_id != t1.parent_Id
)

另一种选择是使用cte:

WITH CTE AS
(
    SELECT
        gen_id, gen_name, parent_id, COUNT(*) OVER(PARTITION BY gen_id) As cnt
    FROM
        table
    WHERE
      parent_id in (1,2,3,4)
)

SELECT gen_id, gen_name, parent_id
FROM CTE
WHERE cnt > 1

答案 1 :(得分:0)

简单删除计数并按

分组
SELECT
   gen_id, gen_name, parent_id
FROM
   table
WHERE
   parent_id in (1,2,3,4)