Sql 选择行数大于1的行

Sql 选择行数大于1的行,sql,google-bigquery,Sql,Google Bigquery,我使用bigquery有一个如下表: 身份证件 年 月 出售 行号 111 2020 11 1000 1. 111 2020 12 2000 2. 112 2020 11 3000 1. 113 2020 11 1000 1. 您可以使用窗口功能: select t.* except (cnt) from (select t.*, count(*) over (partition by id) as cnt from t ) t where cnt

我使用bigquery有一个如下表:

身份证件 年 月 出售 行号 111 2020 11 1000 1. 111 2020 12 2000 2. 112 2020 11 3000 1. 113 2020 11 1000 1.
您可以使用窗口功能:

select t.* except (cnt)
from (select t.*,
             count(*) over (partition by id) as cnt
      from t
     ) t
where cnt > 1;
应用于聚合查询时:

SELECT iym.* EXCEPT (cnt)
FROM (SELECT id, year, month, 
             SUM(sales) as sales, 
             ROW_NUMBER() OVER (Partition by id ORDER BY id ASC) AS row_number
             COUNT(*) OVER(Partition by id ORDER BY id ASC) AS cnt
      FROM table
      GROUP BY id, year, month
     ) iym
WHERE cnt > 1;

您可以使用窗口功能:

select t.* except (cnt)
from (select t.*,
             count(*) over (partition by id) as cnt
      from t
     ) t
where cnt > 1;
应用于聚合查询时:

SELECT iym.* EXCEPT (cnt)
FROM (SELECT id, year, month, 
             SUM(sales) as sales, 
             ROW_NUMBER() OVER (Partition by id ORDER BY id ASC) AS row_number
             COUNT(*) OVER(Partition by id ORDER BY id ASC) AS cnt
      FROM table
      GROUP BY id, year, month
     ) iym
WHERE cnt > 1;

您可以按照下面的示例包装查询

select * except(flag) from (
  select *, countif(row_number > 1) over(partition by id) > 0 flag 
  from (YOUR_ORIGINAL_QUERY)
)
where flag   
所以它看起来像

select * except(flag) from (
  select *, countif(row_number > 1) over(partition by id) > 0 flag 
  from (
    SELECT id, 
    year, 
    month, 
    SUM(sales) as sales, 
    ROW_NUMBER() OVER(Partition by id ORDER BY id ASC) AS row_number
    FROM table
    GROUP BY id, year, month
  )
)
where flag   
因此,当应用于问题中的样本数据时,它将产生以下输出


您可以按照下面的示例包装查询

select * except(flag) from (
  select *, countif(row_number > 1) over(partition by id) > 0 flag 
  from (YOUR_ORIGINAL_QUERY)
)
where flag   
所以它看起来像

select * except(flag) from (
  select *, countif(row_number > 1) over(partition by id) > 0 flag 
  from (
    SELECT id, 
    year, 
    month, 
    SUM(sales) as sales, 
    ROW_NUMBER() OVER(Partition by id ORDER BY id ASC) AS row_number
    FROM table
    GROUP BY id, year, month
  )
)
where flag   
因此,当应用于问题中的样本数据时,它将产生以下输出

试试这个:

使用tmp作为选择id, 年 月 以销售额作为销售额, 行号按id超额分配按id订单按id ASC作为行号 从桌子上 按id、年份、月份分组 从存在的tmp a中选择*从tmp b中选择1,其中a.id=b.id和b.row_编号=2 这是一个非常明显存在的SQL语句

使用tmp作为选择id, 年 月 以销售额作为销售额, 行号按id超额分配按id订单按id ASC作为行号 从桌子上 按id、年份、月份分组 从存在的tmp a中选择*从tmp b中选择1,其中a.id=b.id和b.row_编号=2
这是一个非常明显存在的SQL语句。非常感谢你。你是个救生员多姆。非常感谢你。你是个救生员D