如何从我的表中过滤某些记录 - bigquery

时间:2016-06-29 16:15:35

标签: sql select google-bigquery

我的桌子有product_name,groups(a,b,c,d) 我希望获得分组a,bd但不是c的所有产品。

我给出了以下查询,但我没有得到预期的结果

SELECT
prod_name,group, COUNT(group) AS Count
FROM
  [prod.table]
WHERE
prod NOT IN('c')
AND prod IN('a'.'b','d')

table below

从上表中,查询必须只获取prod2,因为它不在组c中。

我可以使用数据透视表轻松完成此操作,只需排除c组并包括a,b,d。我正在寻找类似的东西。

1 个答案:

答案 0 :(得分:1)

尝试以下

SELECT
  product, GROUP_CONCAT_UNQUOTED(gr) groups, COUNT(gr) AS cnt
FROM (
  SELECT product, gr FROM 
    (SELECT 'Prod1' AS product,'a' AS gr), 
    (SELECT 'Prod1' AS product,'b' AS gr),
    (SELECT 'Prod1' AS product,'c' AS gr), 
    (SELECT 'Prod1' AS product,'d' AS gr), 
    (SELECT 'Prod2' AS product,'a' AS gr), 
    (SELECT 'Prod2' AS product,'b' AS gr), 
    (SELECT 'Prod2' AS product,'d' AS gr), 
    (SELECT 'Prod3' AS product,'a' AS gr), 
    (SELECT 'Prod3' AS product,'b' AS gr), 
    (SELECT 'Prod3' AS product,'c' AS gr), 
    (SELECT 'Prod3' AS product,'d' AS gr)
) 
GROUP BY product 
HAVING NOT ',' + groups + ',' CONTAINS ',c,'
AND ',' + groups + ',' CONTAINS ',a,'
AND ',' + groups + ',' CONTAINS ',b,'
AND ',' + groups + ',' CONTAINS ',d,'
  

但我正在寻找不在c组但在c组中的产品数量   其他团体。

SELECT
  COUNT(product) AS products
FROM (
  SELECT
    product, GROUP_CONCAT_UNQUOTED(gr) groups
  FROM (
    SELECT product, gr FROM 
      (SELECT 'Prod1' AS product,'a' AS gr), 
      (SELECT 'Prod1' AS product,'b' AS gr),
      (SELECT 'Prod1' AS product,'c' AS gr), 
      (SELECT 'Prod1' AS product,'d' AS gr), 
      (SELECT 'Prod2' AS product,'a' AS gr), 
      (SELECT 'Prod2' AS product,'b' AS gr), 
      (SELECT 'Prod2' AS product,'d' AS gr), 
      (SELECT 'Prod3' AS product,'a' AS gr), 
      (SELECT 'Prod3' AS product,'b' AS gr), 
      (SELECT 'Prod3' AS product,'c' AS gr), 
      (SELECT 'Prod3' AS product,'d' AS gr)
  ) 
  GROUP BY product 
  HAVING NOT ',' + groups + ',' CONTAINS ',c,'
  AND ',' + groups + ',' CONTAINS ',a,'
  AND ',' + groups + ',' CONTAINS ',b,'
  AND ',' + groups + ',' CONTAINS ',d,'
)